Skip to content

Instantly share code, notes, and snippets.

@jetsuit
Created July 6, 2017 15:10
Show Gist options
  • Save jetsuit/9b78be26ebd61f33c1c31e09a0ff1165 to your computer and use it in GitHub Desktop.
Save jetsuit/9b78be26ebd61f33c1c31e09a0ff1165 to your computer and use it in GitHub Desktop.
PHP group by key value in multi array
$arr = [
[
'itemId' => 1,
'itemDescription' => 'ItemDescription',
'product' => 'productA',
'productDescription' => 'ProdADesc'
],
[
'itemId' => 1,
'itemDescription' => 'ItemDescription',
'product' => 'productB',
'productDescription' => 'ProdBDesc'
],
[
'itemId' => 1,
'itemDescription' => 'ItemDescription',
'product' => 'productC',
'productDescription' => 'ProdCDesc'
],
];
foreach ($arr as $key => $val){
$resultKey = array_search($val['itemId'], array_column($result, 'itemId'));
if($resultKey === false){
$result[$key]['itemId'] = $val['itemId'];
$result[$key]['itemDescription'] = $val['itemDescription'];
$result[$key]['products'][] = [
'product' => $val['product'],
'productDescription' => $val['productDescription']
];
}else{
$result[$resultKey]['products'][] = [
'product' => $val['product'],
'productDescription' => $val['productDescription']
];
}
}
/*********** Result array **********************
/var/www/zug/src/ApiBundle/Controller/ConversationsController.php:79:
array (size=1)
0 =>
array (size=3)
'itemId' => int 1
'itemDescription' => string 'ItemDescription' (length=15)
'products' =>
array (size=3)
0 =>
array (size=2)
'product' => string 'productA' (length=8)
'productDescription' => string 'ProdADesc' (length=9)
1 =>
array (size=2)
'product' => string 'productB' (length=8)
'productDescription' => string 'ProdBDesc' (length=9)
2 =>
array (size=2)
'product' => string 'productC' (length=8)
'productDescription' => string 'ProdCDesc' (length=9)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment