P
P
PoodingRex2017-03-06 22:10:21
PHP
PoodingRex, 2017-03-06 22:10:21

How to split an array into groups by values?

Good day to all. The question is amateurish, but I don’t even know where it can be viewed.
In general, I have an array, the results of which need to be grouped by the order_id value. That is, for example, it should be like this:
- Beginning of the series -
Product 4
Product 1
- End of the series -
- Beginning of the series -
Product 1
Product 3
- End of the series -
Please tell me how this is possible do. Preferably with an example.
Arrays look like this:

Array ( 
    [0] => Array ( [name] => Товар 4 [order_id] => 12 ) 
    [1] => Array ( [name] => Товар 1 [order_id] => 12 ) 
    [2] => Array ( [name] => Товар 1 [order_id] => 13 ) 
    [3] => Array ( [name] => Товар 3 [order_id] => 13 ) 
    [4] => Array ( [name] => Товар 1 [order_id] => 14 ) 
    [5] => Array ( [name] => Товар 2 [order_id] => 14 ) 
    [6] => Array ( [name] => Товар 3 [order_id] => 15 ) 
    [7] => Array ( [name] => Товар 2 [order_id] => 16 ) 
    [8] => Array ( [name] => Товар 3 [order_id] => 16 ) 
)

Tried like this, but gives each value in a wrapper
foreach ($res as $row) {
    echo 'начало ряда';
    echo  $row['name'];
    echo 'конец ряда';
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Pupkin, 2017-03-07
@HectorPrima

$res = array();
$res[] = array('name'=>4,'order_id' => 12);
$res[] = array('name'=>1,'order_id' => 12);
$res[] = array('name'=>1,'order_id' => 13);
$res[] = array('name'=>3,'order_id' => 13);

$prev = 0;
foreach ($res as $row) {
    if ($prev <> $row['order_id'])
    {
    	if ($prev > 0)
    		echo "конец ряда\n";
    	echo "начало ряда\n";
    }
    echo  $row['name']."\n";
    $prev = $row['order_id'];
}
if ($row['order_id'])
  echo "конец ряда\n";

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question