PHP reorder multidimensional array based on single dimensional array - php

multidimensional array
Array
(
[0] => Array
(
[ID] => 5068
[Item] => 2737
[Unit] => 15
)
[1] => Array
(
[ID] => 5067
[Item] => 2737
[Unit] => 13
)
)
single dimensional array
Array (
[0] => 11
[1] => 13
[2] => 15
)
Expected output:
Array
(
[0] => Array
(
[ID] => 5067
[Item] => 2737
[Unit] => 13
)
[1] => Array
(
[ID] => 5068
[Item] => 2737
[Unit] => 15
)
)
It not necessary that single dimensional array must be in ASC/DESC order. I want to reorder multidimensional array according to single dimensional array based on unit value. How can I achieve this?

Maybe something like this would work?
$multiDimArray = [
0 => [
'ID' => 5068,
'Item' => 2737,
'Unit' => 15
],
1 => [
'ID' => 5067,
'Item' => 2737,
'Unit' => 13
]
];
$singleDim = [
11,13,15
];
usort($multiDimArray,function($a,$b){
global $singleDim;
return ($singleDim[0] >= $a['Unit']) ? -1 :1;
});
print_r($multiDimArray);
there's something in back of my head that tells me I'm missing something. But feel free to give it a go.

Assuming that the values in the single array all map to a value in Unit, you could loop the single dimensional array and then loop the values in the multidimensional array.
In the inner loop use in_array to check if the value from the single dimensional array occurs in the multidimensional array. If it does, you could for example add it to a new array.
$result = [];
foreach ($singleDimension as $sm) {
foreach ($multiDimensional as $md) {
if (in_array($sm, $md)) {
$result[] = $md;
}
}
}
Demo

Related

Creating a new associative array using values of the nested multi dimensional array in php

I have following multi dimensional array, I'm getting this from an API via curl request.
Array
(
[0] => Array
(
[id] => 1
[name] => David Warner
[type] => batter
[country] => Aus
[age] => 33
[runs] => 11100
[wickets] => 12
[catches] => 16
[format] => Array
(
[0] => Array
(
[Domestic] => Array
(
[0] => Array
(
[ODI] => 73
[Tests] => 34
[T20] => 90
)
)
)
)
)
[1] => Array
(
[id] => 2
[name] => Mark Wood
[type] => bowler
[country] => Eng
[age] => 34
[runs] => 200
[wickets] => 120
[catches] => 2
[format] => Array
(
[0] => Array
(
[Domestic] => Array
(
[0] => Array
(
[ODI] => 40
[Tests] => 49
[T20] => 12
)
)
)
)
)
)
I'm trying to create a new array which includes only the "[T20]" values.
My desired out put should look similar to the following array
array:2 [▼
0 => "90"
1 => "12"
]
So far, I've tried following methods...
$newArr_t20 = array_column($result_3['cricketers']['player']['format']['Domestic'], "T20");
Since I'm using laravel then I tried following as well,
use \Illuminate\Support\Arr;
$newArr_t20 = Arr::pluck($result_3, 'cricketers.player.format.Domestic.T20');
But nothing is working for me...
You can try this:
$array = 'Your array...';
$t20_values = [];
foreach ($array as $value) {
foreach ($value['format'] as $format) {
foreach ($format['Domestic'] as $domestic) {
if (isset($domestic['T20'])) {
$t20_values[] = $domestic['T20'];
}
}
}
}
dd($t20_values);
Using Laravel the collection helper Collection::flatten() should be the right way;
$data = collect($apiData)->flatten(4)->pluck('T20')->all();
Explanation:
Transform your array into a collection to be able to use the Laravel collection's provided helpers:
collect($apiData)
Transform your multidimensional array into a single dimensional one, which is nothing more than the array at the n-th depth (4 here in this case):
collect($apiData)->flatten(4)
Map this array into an array having only the values of the T20 key
collect($apiData)->flatten(4)->pluck('T20')
Get the array representation of the collection
collect($apiData)->flatten(4)->pluck('T20')->all()

Merge all subarrays on second level of a multidimensional array [duplicate]

This question already has answers here:
How to array_merge_recursive() an array?
(2 answers)
Closed 5 months ago.
I need to find a way to combine elements by key in a new array, such that I end up with just one key containing all values for that key (found elsewhere in the parent array). This will make more sense when you see the example below:
Array
(
[0] => Array
(
[AAA] => Array
(
[0] => F104_f58f85f9dbbe1ce083ca09a6f9ace679
[1] => F104_480e9f231b2b5a138f8aa5570ffa8634
[2] => F104_d5fde0ad2499052e0eae6dec451f9385
)
[BBB] => Array
(
[0] => F44_e2e052e7b78abbae02ffcf7413302a0c
[1] => F44_4d4da736509babebba7433b203b16753
)
)
[1] => Array
(
[AAA] => Array
(
[0] => F104_480e9f231b2b5a138f8aa5570ffa8634
)
[ZZZ] => Array
(
[0] => F20_5e742bc21f41a14243c3f72b9fa4815e
)
)
)
The original array is quite large with more keys and values. But everything is in the same structure depicted above.
I'd like to read that in, and return
Array
(
[AAA] => Array
(
[0] => F104_f58f85f9dbbe1ce083ca09a6f9ace679
[1] => F104_480e9f231b2b5a138f8aa5570ffa8634
[2] => F104_d5fde0ad2499052e0eae6dec451f9385
[4] => F104_480e9f231b2b5a138f8aa5570ffa8634
)
[BBB] => Array
(
[0] => F44_e2e052e7b78abbae02ffcf7413302a0c
[1] => F44_4d4da736509babebba7433b203b16753
)
[ZZZ] => Array
(
[0] => F20_5e742bc21f41a14243c3f72b9fa4815e
)
)
What's the least painful and most efficient way of accomplishing this?
Using array_merge_recursive() and array unpacking to pass the separate parts into it...
print_r(array_merge_recursive(...$array));
gives...
Array
(
[AAA] => Array
(
[0] => F104_f58f85f9dbbe1ce083ca09a6f9ace679
[1] => F104_480e9f231b2b5a138f8aa5570ffa8634
[2] => F104_d5fde0ad2499052e0eae6dec451f9385
[3] => F104_480e9f231b2b5a138f8aa5570ffa8634
)
[BBB] => Array
(
[0] => F44_e2e052e7b78abbae02ffcf7413302a0c
[1] => F44_4d4da736509babebba7433b203b16753
)
[ZZZ] => Array
(
[0] => F20_5e742bc21f41a14243c3f72b9fa4815e
)
)
You could use array_map() to traverse the parent array. And use another foreach loop to combine the values. Please note the $output array is passed by reference.
$inputArray = [
0 => [
'AAA' => [
0 => 'F104_f58f85f9dbbe1ce083ca09a6f9ace679',
1 => 'F104_480e9f231b2b5a138f8aa5570ffa8634',
2 => 'F104_d5fde0ad2499052e0eae6dec451f9385',
],
'BBB' => [
0 => 'F44_e2e052e7b78abbae02ffcf7413302a0c',
1 => 'F44_4d4da736509babebba7433b203b16753',
]
],
1 => [
'AAA' => [
0 => 'F104_480e9f231b2b5a138f8aa5570ffa8634'
],
'ZZZ' => [
0 => 'F20_5e742bc21f41a14243c3f72b9fa4815e'
]
]
];
$output = [];
array_map(function($values) use (&$output){
foreach ($values as $key => $value){
if(empty($output[$key])){
$output[$key] = $value;
}else{
$output[$key] = array_merge($output[$key], $value);
}
}
}, $inputArray);
print_r($output);
Here is a working example http://sandbox.onlinephpfunctions.com/code/97909ce93184fad6c33af8eb48d184ae86438774

Removing subarrays that share a key-value pair with another multidimensional array

I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.
$array1 = Array
(
[0] => Array
(
[stu_id] => 1
[name] => mr.a
)
[1] => Array
(
[stu_id] => 3
[name] => mr.b
)
)
$array2 = Array
(
[0] => Array
(
[id] => 1
[stu_id] => 1
[data] => abc
)
[1] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
[3] => Array
(
[id] => 3
[stu_id] => 3
[data] => aaa
)
)
$result_array = Array
(
[0] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
)
I tried array_diff, $result_array = array_diff($array2, $array1); but it's not working.
Please help me to do this.
Temporarily assign keys using array_column() with stud_id (NULL retains the full subarray data), then use array_diff_key() to filter, and array_values() to reset the keys:
Code: (Demo)
$array1=[
['stu_id'=>1,'name'=>'mr.a'],
['stu_id'=>3,'name'=>'mr.b']
];
$array2=[
['id'=>1,'stu_id'=>1,'data'=>'abc'],
['id'=>2,'stu_id'=>2,'data'=>'xyz'],
['id'=>3,'stu_id'=>3,'data'=>'aaa']
];
//var_export(array_column($array1,NULL,'stu_id'));
//var_export(array_column($array2,NULL,'stu_id'));
var_export(array_values(array_diff_key(array_column($array2,NULL,'stu_id'),array_column($array1,NULL,'stu_id'))));
Output:
array (
0 =>
array (
'id' => 2,
'stu_id' => 2,
'data' => 'xyz',
),
)
If you'd like to use a foreach loop structure, generate a filtering array of stu_id's from $array1 and write a conditional check on each iteration of $array2. This method doesn't not modify the original arrays, so they can be reused "down script".
Code:
$stu_ids=array_column($array1,'stu_id');
foreach($array2 as $row){
if(!in_array($row['stu_id'],$stu_ids)){
$result[]=$row; // auto-index the qualifying subarrays
}
}
var_export($result);
// same result as above method
foreach($array1 as $data1){
foreach($array2 as $k => $data2){
if($data2["stu_id"] == $data1["stu_id"]){
unset($array2[$k]);
break;
}
}
}
$result_array = $array2;

Sorting multidimensional array in PHP with key values [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 5 years ago.
I need to sort this array below, in descending order, but I'm currently stuck and can't think of a simple solution.
This is the array structure:
$data = Array
(
[Name1] => Array
(
[1] => 40-45
[0] => 124791.63
)
[Name2] => Array
(
[1] => 46
[0] => 2624.7
)
[Name3] => Array
(
[1] => 50
[0] => 37784.27
)
[Name4] => Array
(
[1] => 52
[0] => 1008
)
)
I want to sort it by value $data[Name1][0], in the descending order, as you can see the current array is not sorted since the values go like this:
124791.63 -- 2624.7 -- 37784.27 ...etc
Is there any simple solution to this? I googled, but I couldn't find an answer to this specific problem.
An option to do this is use uasort.
For example:
$data = [
'Name1' => [
"124791.63",
"40-45"
],
'Name2' => [
"2624.7",
"46"
],
'Name3' => [
"37784.27",
"50"
],
'Name4' => [
"1008",
"52"
]
];
function sortByValue($a, $b) {
return $a[0] < $b[0];
}
uasort($data, 'sortByValue');
echo "<pre>";
print_r($data);
Will result in:
Array
(
[Name1] => Array
(
[0] => 124791.63
[1] => 40-45
)
[Name3] => Array
(
[0] => 37784.27
[1] => 50
)
[Name2] => Array
(
[0] => 2624.7
[1] => 46
)
[Name4] => Array
(
[0] => 1008
[1] => 52
)
)

merging of 2 identical keys in one array

Need help from the team,
I have this scenario of having 2 identical keys in each array with different values, i want them to be merged into one key were the values also are in it
example:
arrayData1(
[2] => Array
(
[EXP1] => Array (records...)
[EXP2] => Array (records...)
)
)
arrayData2(
[2] => Array
(
[EXP3] => Array (records...)
[EXP4] => Array (records...)
)
)
Having the output like this:
arrayFinal (
[2] => Array
(
[EXP1] => Array (records...)
[EXP2] => Array (records...)
[EXP3] => Array (records...)
[EXP3] => Array (records...)
)
)
Thanks!
First of all you cannot have two same keys in a single array, what you can do is use the array_merge_recursive function in php to merge both the arrays, and the repeating keys will have a new array with all the repeating key values..
$array1 = [
'EXP1' => [1,2,3],
'EXP2' => [2,3,4]
];
$array2 = [
'EXP2' => [5,6,7],
'EXP3' => [8,9,10]
];
Now there are two EXP2 keys, so when you use array_merge_recursive() you get something like this,
print_r(array_merge_recursive($array1, $array2));
//output Array (
[EXP1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[EXP2] => Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 6
[5] => 7
)
[EXP3] => Array
(
[0] => 8
[1] => 9
[2] => 10
)
)

Categories