Need help with - explode() implode() and other

In product.php page

$getproduct = (int)$_GET['product'];
$u = do_mysql_query("SELECT id, product_price, product_weight FROM prices WHERE product_id = '".$getproduct."' ORDER BY id ASC") or sqlerr(__FILE__, __LINE__);
	if (mysqli_num_rows($u) >= 1) {
	while ($result_go = mysqli_fetch_array($u)){
print("<p title=\\"&#1062;&#1077;&#1085;&#1072;: ".number_format($result_go['product_price'])."&#1088;&#1091;&#1073;.\\" align=\\"left\\"><small><input type=\\"checkbox\\" name=\\"price_id_yes\\" value=\\"".$result_go['id']."\\" /> <b>".number_format($result_go['product_weight'])."&#1075;. - <font color=\\"#FF0000\\" size=\\"1\\">".number_format($result_go['product_price'])."&#1088;&#1091;&#1073;.</font></b></small></p>");
} }

so $_POST[‘price_id_yes’] extract the data like simple id number(s)

Now in add_order.php (where check the data for update or insert new)

If posts (one or more) $_POST[‘price_id_yes’] add _+1

Here is explain what exactly i need

if one id=102 result should be 102_1 (with first choices) ,

if three id’s 102,105,106 result should be 102_1|105_1|106_1 (with first chooises)

Now if some one wanna more and send second POST with id 105 only (for now) result should be 102_1|105_2|106_1 (because +1)

How to do all of this ? (i know that i need work with explode and implode here, i just can’t get good result)

implode(‘_’ -> (to work id_sum) , implode(’ | ’ (to result of all data id_sum|id_sum|id_sum|id_sum)

Something like this might work.

<?php
//Assuming data comes from single DB field.  I will call $data
//Example
$_POST['price_id_yes'] = "105";
$data = "102_1|105_1";
		
$old_data = array();
$new_data = array();

if(!empty($data)){
	$data_array = explode("|",$data);
	foreach($data_array as $d){
		$d_array = explode("_",$d);
		$old_data[$d_array[0]] = $d_array[1];
	}
	if(array_key_exists($_POST['price_id_yes'],$old_data)){
		foreach($old_data as $id => $num){
		
			if ($_POST['price_id_yes'] == $id){
				$new_num = $num+1;
				$new_data[] = $id . "_" . $new_num;	
			}else{
				$new_data[] = $id . "_" . $num;		
			}
			
		}
	}else{
		foreach($old_data as $id => $num){
			$new_data[] = $id . "_" . $num;
		}
		$new_data[] = $_POST['price_id_yes'] . "_" . 1;
	}
}else{
	$new_data[] = $_POST['price_id_yes'] . "_" . 1;
}

$new_data = implode("|",$new_data);	
?>

Thanks Drummin , it’s work 75% …
The proplem is

1. Get error

Warning: array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in Z:\\home\\localhost\\www\\add_order.php on line 28

2. If someone send second POST with one of products, its do not edit :frowning: only add new value .
Example: Before

67_1|68_1

after i chooise second time, one or more it was add (Array_1 and maximum second times

67_1|68_1|Array_1|Array_1

All the page

<?
require_once("include/bittorrent.php");
dbconn();

$add_product = (int)$_POST['product_id'];
$ip = getenv('REMOTE_ADDR');
if($CURUSER){
$userid = $CURUSER['id'];
$raw_results = do_mysql_query("SELECT * FROM sale WHERE userid='".$userid."' AND id_prod='".$add_product."'") or sqlerr(__FILE__, __LINE__);
}else{
$userid = 0;
$raw_results = do_mysql_query("SELECT * FROM sale WHERE ip='".$ip."' AND userid='".$userid."' AND id_prod='".$add_product."'") or sqlerr(__FILE__, __LINE__);
}
$datetime = get_date_time();
$hash = wordwrap(strtoupper(md5($datetime . $userid . $ip)),6,'-',true);
$price_id_yes = $_POST['price_id_yes'];
$prod = mysqli_fetch_array($raw_results);
$data = $prod['prices_id'];
$old_data = array();
$new_data = array();

if(!empty($data)){
    $data_array = explode("|",$data);
    foreach($data_array as $d){
        $d_array = explode("_",$d);
        $old_data[$d_array[0]] = $d_array[1];
    }
    if(array_key_exists($price_id_yes, $old_data)){
        foreach($old_data as $id => $num){

            if ($price_id_yes == $id){
                $new_num = $num+1;
                $new_data[] = $id . "_" . $new_num;
            }else{
                $new_data[] = $id . "_" . $num;
            }
        }
    }else{
        foreach($old_data as $id => $num){
            $new_data[] = $id . "_" . $num;
        }
        $new_data[] = $price_id_yes . "_" . 1;
    }
    $update[] = "prices_id = ".sqlesc(implode("|",$new_data));
	$update[] = "date = ".sqlesc($datetime);
mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE sale SET ".join(",", $update)." WHERE id = ".$prod['id']) or sqlerr(__FILE__, __LINE__);

}else{
foreach($price_id_yes as $item){
    $new_data[] = $item . "_" . 1;
	$prices_id = implode("|",$new_data);
}

mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO sale (ip, userid, date, id_prod, prices_id, hash)
VALUES(".sqlesc($ip).", ".sqlesc($userid).", ".sqlesc($datetime).", ".sqlesc($add_product).", ".sqlesc($prices_id).", ".sqlesc($hash).")") or sqlerr(__FILE__, __LINE__);
}
header("Location: ./index.php?i=sale&order_id={".$hash."}");
?>

Any ideas ? :slight_smile:

Hi Smolf3d,

Something like this should work:


// Serialize/unserialize functions
function serialize_prices_id(array $data)
{
	$output = array();
	foreach ($data as $id => $count) {
		$output[] = $id.'_'.$count;
	}

	return implode('|', $output);
}

function unserialize_prices_id($prices_string)
{
	$data = array();
	foreach (explode('|', $prices_string) as $product) {
		list($id, $count) = explode('_', $product);
		$data[$id] = $count;
	}

	return $data;
}

// Updating the data
$submitted_ids = explode(',', $_POST['price_id_yes']);
$data = unserialize_prices_id($prod['prices_id']);

foreach ($submitted_ids as $id) {
	if (array_key_exists($id, $data)) {
		$data[$id] += 1;
	} else {
		$data[$id] = 1;
	}
}

$prices_id = serialize_prices_id($data);

I’ve moved the code for converting the data to and from a string into separate functions, which helps to keep the main code tidier.

fretburner’s solution looks very nice.

Smolf3d, do you realize that something like

67_1|68_1|Array_1|Array_1

means you would trying to concatenate an array to a string without looping inside it.

Something like

$s1 = 'foo';
$a = [1,2,3];
$s2 = $s1 . $a;
echo $s2; // output: fooArray

is a demonstration of the problem

Also I have to question why you want to construct a string such as 67_1|68_2 etc. The correct thing to do is to have those numbers (the id and the quantity) stored as separate values in your database

I agree. For a properly designed application where that type of coding is required it is just about the simplest part of the entire code. If you can’t work out that trivial part then you will never get the rest of the code to work. If that isn’t the most trivial part of the code then most likely the design is wrong and you shouldn’t be trying to do that at all.

I will try to explain :slight_smile:

In my company shop i have products with many prices (in one product can be 5 others prices, group by weight).

Because i have 2 tables (1 where product info and 2 where price with weight) , i don’t found the option to add unlimited prices in one id product with sums of them.

I upload some pics how it looked

And this is tables

CREATE TABLE IF NOT EXISTS `production` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `image` varchar(100) NOT NULL DEFAULT '',
  `name` varchar(100) NOT NULL,
  `napolnitel` text NOT NULL,
  `code_production` varchar(20) NOT NULL,
  `catname` int(10) NOT NULL,
  `about_product` text NOT NULL,
  `info_pack` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `prices` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `product_id` int(10) NOT NULL,
  `product_price` int(10) NOT NULL,
  `product_weight` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM;

CREATE TABLE IF NOT EXISTS `sale` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ip` varchar(15) NOT NULL DEFAULT '',
  `userid` int(11) NOT NULL DEFAULT '0',
  `date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `id_prod` int(10) DEFAULT NULL,
  `prices_id` text NOT NULL,
  `hash` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

fretburner - Thank you i will look and check :slight_smile:

fretburner - Work perfect! Thank you very much ! :slight_smile:

i don’t found the option to add unlimited prices in one id product with sums of them.
Yes you do. Just add a quantity column to the sale table. Boom! Unless there’s some reason you can’t alter the database design? But if that was the case that would be a ridiculous state of affairs that any developer should consider themselves to be reasonably entitled to correct.