I am using laravel framework to develop API's. i was stuck at one point i have one array with duplicate keys and random values like following
array:35 [
0 => array:1 [
"Contact Info" => 75
]
1 => array:1 [
"Contact Info" => 76
]
2 => array:1 [
"Contact Info" => 77
]
3 => array:1 [
"Contact Info" => 78
]
4 => array:1 [
"Contact Info" => 79
]
12 => array:1 [
"Contact Info" => 596
]
13 => array:1 [
"Contact Info" => 597
]
14 => array:1 [
"Contact Info" => 593
]
15 => array:1 [
"Contact Info" => 595
]
16 => array:1 [
"Contact Info" => 588
]
17 => array:1 [
"Contact Info" => 594
]
18 => array:1 [
"Contact Info" => 591
]
19 => array:1 [
"Contact Info" => 592
]
20 => array:1 [
"Contact Info" => 626
]
21 => array:1 [
"Contact Info" => 590
]
22 => array:1 [
"Address Info" => 85
]
23 => array:1 [
"Address Info" => 86
]
24 => array:1 [
"Address Info" => 87
]
]
i want the above like following array,note the array key will be dynamic not static one .can anyone please help me to acheive this one.
$temp = ['contact Info' => ['75','76',77',78'....] ,'Address Info' =. ['85','86','87'...]];
CodePudding user response:
In case your keys are also dynamic you can try below code:
$temp = [];
foreach ($array as $item) {
foreach ($item as $key => $itemValue) {
$temp[$key][] = $itemValue;
}
}
print_r($temp);
Hope it helps the arrray_column()
solution is more efficient in case of not dynamic.
CodePudding user response:
You can simply use array_column()
like below:
$finalAray = ['contact Info'=> array_column($array,'Contact Info'),'Address Info'=> array_column($array,'Address Info')];
Sample output: https://3v4l.org/dqOk0
CodePudding user response:
You can group these and to do unique and sort at finish.
<?php
$data = [
[
"Contact Info" => 5
],
[
"Address Info" => 85
],
[
"Address Info" => 885
],
[
"Contact Info" => 592
],
[
"Address Info" => 85
],
[
"Address Info" => 8
],
[
"Contact Info" => 3
],
[
"Contact Info" => 3
],
];
$dumpData = ['Contact Info'=>array_unique(array_column($data,'Contact Info')),'Address Info'=> array_unique(array_column($data,'Address Info'))];
sort($dumpData['Contact Info']);
sort($dumpData['Address Info']);
echo'<pre>';
print_r($dumpData);