E
E
ecig2018-07-25 18:07:34
PHP
ecig, 2018-07-25 18:07:34

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

It is necessary to extract this data using PHP in the form of an array of the format
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

2 answer(s)
N
nozzy, 2018-07-25
@nozzy

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);
});

S
Sergey c0re, 2019-10-14
@erge

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`

an example of working on sqlfiddle
in PHP is something like this:
$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 question

Ask a Question

731 491 924 answers to any question