Answer the question
In order to leave comments, you need to log in
How to read data from a MySQL table and insert it into an array with subsequent writing?
Good day! I can't come up with a solution to the problem.
I have a MySQL table like this:
ID | SESSION | PRODUCT ID | PRICE | QUANTITY
72 222145 4454512274 2000 1
73 222145 6561548945 3000 2
74 222145 5646168845 1000 1
222145 =>
( PRODUCT 1 => (PRODUCT ID => 4454512274, PRICE=> 2000, QUANTITY=> 1),
PRODUCT 2 => (PRODUCT ID => 6561548945, PRICE=> 3000, QUANTITY=> 2) ,
PRODUCT 3 => (PRODUCT ID => 5646168845, PRICE=> 1000, QUANTITY=> 1) )
Answer the question
In order to leave comments, you need to log in
Laravel has Collection and groupBy for this.
To use Collection without Laravel
install:
composer require tightenco/collect
<?php
require '/vendor/autoload.php';
use Illuminate\Support\Collection;
$array = array(
array('id' => '7', 'name' => 'foo'),
array('id' => '7', 'name' => 'foo2'),
array('id' => 10, 'name' => 'bar'),
array('id' => 10, 'name' => 'bar2'),
array('id' => 11, 'name' => 'bar3')
);
$collection = new Collection($array);
$grouped = $collection->groupBy('id');
$grouped->each(function ($item, $key) {
print_r($key . PHP_EOL);
print_r($item);
});
You can wrap the query result in a JSON form, and in php apply json_decode($result, true)
SQL query to the result:
SELECT
CONCAT(
'{"',`session`,'":{',
GROUP_CONCAT('"PRODUCT ', @i:[email protected]+1, '":{"PRODUCT ID":',product_id,',"PRICE":',price,',"QUANTITY":',quantity,'}' separator ','),
'}}') AS value
FROM carts, (SELECT @i:=0) X
WHERE `session` = 222145
GROUP BY `session`
$session_id = 222145;
$sql = 'SELECT
CONCAT(
\'{"\',`session`,\'":{\',
GROUP_CONCAT(\'"PRODUCT \', @i:[email protected]+1, \'":{"PRODUCT ID":\',product_id,\',"PRICE":\',price,\',"QUANTITY":\',quantity,\'}\' separator \',\'),
\'}}\') AS value
FROM carts, (SELECT @i:=0) X
WHERE `session` = %s
GROUP BY `session`';
$arr = json_decode(mysql_result(mysql_query(sprintf($sql, $session_id)),0), true);
var_dump( $arr );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question