Multidimensional array
There is an array:
$cars = array(
'1' => array('id'=>1, 'producer'=>'bmw', 'model'=>'x5', 'sale'=>'10', 'price'=>'100', 'uniq'=>'1#10#100'),
'2' => array('id'=>1, 'producer'=>'bmw', 'model'=>'x5', 'sale'=>'10', 'price'=>'100', 'uniq'=>'1#10#100'),
'3' => array('id'=>1, 'producer'=>'bmw', 'model'=>'x5', 'sale'=>'0', 'price'=>'110', 'uniq'=>'1#0#110'),
'4' => array('id'=>2, 'producer'=>'audi', 'model'=>'a1', 'sale'=>'0', 'price'=>'90', 'uniq'=>'2#0#90'),
'5' => array('id'=>2, 'producer'=>'audi', 'model'=>'a1', 'sale'=>'0', 'price'=>'90', 'uniq'=>'2#0#90')
);
Uniq is formed according to the principle of id#sale#price.
You need to get an array from it:
$unique_cars = array(
'1' => array('id'=>1, 'producer'=>'bmw', 'model'=>'x5', 'sale'=>'10', 'price'=>'100', 'quantity'=>2),
'2' => array('id'=>1, 'producer'=>'bmw', 'model'=>'x5', 'sale'=>'0', 'price'=>'110', 'quantity'=>1),
'3' => array('id'=>2, 'producer'=>'audi', 'model'=>'a1', 'sale'=>'0', 'price'=>'90', 'quantity'=>2)
);
Thank you all for your participation, it's a pity that you can't choose several correct answers at once :)
1
3 answers
$unique_cars = array();
foreach ($cars as $car)
{
if (!isset($unique_cars[$car['uniq']]))
{
$car['quantity'] = 1;
$unique_cars[$car['uniq']] = $car;
unset($unique_cars[$car['uniq']]['uniq']);
}
else
$unique_cars[$car['uniq']]['quantity']++;
}
// странные ключи массивов (строковые numeric, да еще не от 0, а от 1)
// но это твое дело
$indexes = array();
while (count($indexes) < count($unique_cars))
$indexes[] = strval(count($indexes) + 1);
$unique_cars = array_combine($indexes, $unique_cars);
var_dump($unique_cars);
1
Author: Bars, 2013-03-29 08:37:20
The algorithm is as follows:
- Running a loop on all elements of
$cars
- We add each element to the array
$unique_cars
, first comparing the necessary fields: if they are identical, then we increase thequantity
of the corresponding element$unique_cars
What are the difficulties?
2
Author: Zhukov Roman, 2013-03-29 08:00:51
For me, there is so much extra in the resulting array.
It should be like this
$unique_cars = array(
'1' => array('producer'=>'bmw', 'model'=>'x5', 'sale'=>'10', 'price'=>'100', 'quantity'=>2),
'2' => array('producer'=>'bmw', 'model'=>'x5', 'sale'=>'0', 'price'=>'110', 'quantity'=>1),
'3' => array('producer'=>'audi', 'model'=>'a1', 'sale'=>'0', 'price'=>'90', 'quantity'=>2)
);
1
Author: Artem, 2013-03-29 08:21:45