I have a simple two dimensional array like this:
Array
(
[0] => Array
(
[id] => 1
[name] => John
[company] => One
[price] => 12.22
)
[1] => Array
(
[id] => 1
[name] => John
[company] => Two
[price] => 14.33
)
[2] => Array
(
[id] => 2
[name] => Mike
[company] => One
[price] => 15.11
)
[3] => Array
(
[id] => 2
[name] => Mike
[company] => Two
[price] => 10.12
)
[4] => Array
(
[id] => 3
[name] => Paul
[company] => One
[price] => 42.22
)
[5] => Array
(
[id] => 3
[name] => Paul
[company] => Two
[price] => 56.62
)
[6] => Array
(
[id] => 3
[name] => Paul
[company] => Three
[price] => 16.12
)
)
I need to group id
and name
, then create an array with different values something like this:
Array
(
[0] => Array
(
[id] => 1
[name] => John
[companies] => array (
array(
[company] => One
[price] => 12.22
)
array(
[company] => Two
[price] => 14.33
)
)
)
[1] => Array
(
[id] => 2
[name] => Mike
[companies] => array (
array(
[company] => One
[price] => 15.11
)
array(
[company] => Two
[price] => 10.12
)
)
)
[2] => Array
(
[id] => 3
[name] => Paul
[companies] => array (
array(
[company] => One
[price] => 42.22
)
array(
[company] => Two
[price] => 56.62
)
array(
[company] => Three
[price] => 16.12
)
)
)
)
What is the best way to do it with PHP?
This is my attemp:
<?php
$items=array();
$temp = 0;
$companies = array('uno','dos','tres');
foreach ($values as $value) {
if ($temp == $value['id'] )
continue;
else
$temp == $value['id'];
foreach ($companies as $key => $company){
foreach ($values as $item){
if ($item['id'] == $temp && $item['company'] == $key)
$value['company'][$key] = $item['price'];
}
}
$items[] = $value;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…