Answer the question
In order to leave comments, you need to log in
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 )
)
foreach ($res as $row) {
echo 'начало ряда';
echo $row['name'];
echo 'конец ряда';
}
Answer the question
In order to leave comments, you need to log in
$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 questionAsk a Question
731 491 924 answers to any question