I'm having trouble getting to re-arrange an array by the key's duplicate values of the Key 'Company' and making it the value so that it is re-arranged in the code below this one:
Original array:
$array = array(
'number' => 2,
'items' =>
array(
'Company' => 'ABC',
'First' => 'John',
'Last' => 'Doe',
),
array(
'Company' => 'ABC',
'First' => 'Jane',
'Last' => 'Doe',
),
array(
'Company' => 'XYZ',
'First' => 'Peter',
'Last' => 'Pumpkin',
),
);
I want to re-sort the array on the 'Company' value and make it the key, like the example below:
$array = array(
'number' => 2,
'items' =>
array(
'ABC' =>
array(
'First' => 'John',
'Last' => 'Doe'),
array(
'First' => 'Jane',
'Last' => 'Doe'),
'XYZ' =>
array(
'First' => 'Peter',
'Last' => 'Pumpkin'),
)
);
I looked hard in the PHP Docs, so this seems to be a unique type of sort.
$array = array(
'number' => 2,
'items' => array(
array(
'Company' => 'ABC',
'First' => 'John',
'Last' => 'Doe',
),
array(
'Company' => 'ABC',
'First' => 'Jane',
'Last' => 'Doe',
),
array(
'Company' => 'XYZ',
'First' => 'Peter',
'Last' => 'Pumpkin',
)
)
);
$final = $array;
$final['items'] = array();
foreach ($array['items'] as $item) {
$final['items'][$item['Company']] = $item;
unset($final['items'][$item['Company']]['Company']);
}
var_dump($final);
Result:
array (size=2)
'number' => int 2
'items' =>
array (size=2)
'ABC' =>
array (size=2)
'First' => string 'Jane' (length=4)
'Last' => string 'Doe' (length=3)
'XYZ' =>
array (size=2)
'First' => string 'Peter' (length=5)
'Last' => string 'Pumpkin' (length=7)
You can construct the array you want by looping over your original array.
BTW, I think you meant to put another array() to hold all the items in.
$array = array(
'number' => 2,
'items' =>
array(//I assume this was missing in your original Question
array(
'Company' => 'ABC',
'First' => 'John',
'Last' => 'Doe',
),
array(
'Company' => 'ABC',
'First' => 'Jane',
'Last' => 'Doe',
),
array(
'Company' => 'XYZ',
'First' => 'Peter',
'Last' => 'Pumpkin',
),
)
);
$newarray = array();
foreach ($array['items'] as $key=>$val){
$company = $val['Company'];
if (empty($newarray[$company])){
//set a new key to hold our data
$newarray[$company] = array();
}
// because $val contains 'Company', we want to get rid of it
unset($val['Company']);
// add the current item under the company key
$newarray[$company][] = $val;
}
$array['items'] = $newarray;
print_r($array);
I see CodeGodie just answered with a much shorter version of this. :)