Merge php array with dynamic key - php

If I query out the array like this form:
$arr1:
0 =>
'id' => 1,
'name' => 'a'
1 =>
'id' => 2,
'name' => 'b'
2 =>
'id' => 3,
'name' => 'c'
3 =>
'id' => 4,
'name' => 'd'
$arr2:
0 =>
'id' => 1,
'parent' => '1a'
1 =>
'id' => 2,
'parent' => '2b'
2 =>
'id' => 3,
'parent' => '3c'
3 =>
'id' => 4,
'parent' => '4d'
When I need to merge these two I can done it using foreach loop.
The problem comes to when the $arr1 is dynamic data(need to use for pagination), i can't merge well using array_merge due to $arr2 is fixed data.
example:
first time:
$arr1:
0 =>
'id' => 1,
'name' => 'a'
1 =>
'id' => 2,
'name' => 'b'
$arr2:
0 =>
'id' => 1,
'parent' => '1a'
1 =>
'id' => 2,
'parent' => '2b'
2 =>
'id' => 3,
'parent' => '3c'
3 =>
'id' => 4,
'parent' => '4d'
second time:
$arr1:
0 =>
'id' => 3,
'name' => 'c'
1 =>
'id' => 4,
'name' => 'd'
$arr2:
0 =>
'id' => 1,
'parent' => '1a'
1 =>
'id' => 2,
'parent' => '2b'
2 =>
'id' => 3,
'parent' => '3c'
3 =>
'id' => 4,
'parent' => '4d'
I had try using foreach loop
foreach($arr1 as $k => $value){
$group[$k]['parent'] = $arr2[$k]['parent'];
$group[$k]['name'] = $value['name'];
$group[$k]['id'] = $value['id'];
}
It comes to the parent value does not change as $key is fixed.
The expected output should all the element in 1 array:
0 =>
'id' => 1,
'parent' => '1a'
'name'='a'
1 =>
'id' => 2,
'parent' => '2b'
'name'='b'

I think this is what you need...
The easiest way to do this is to re-index the second array with the ID as the key. I use array_column() to do this. Then use the id from $arr1 to access the parent value from the newly indexed array...
$parent = array_column($arr2, 'parent', 'id');
$group = [];
foreach($arr1 as $k => $value){
$group[$k]['parent'] = $parent[$value['id']];
$group[$k]['name'] = $value['name'];
$group[$k]['id'] = $value['id'];
}
In case $arr2 has more information, just use null as the second parameter to array_column(). Then you need to add the column name when you access that array...
$parent = array_column($arr2, null, 'id');
$group = [];
foreach($arr1 as $k => $value){
$group[$k]['parent'] = $parent[$value['id']]['parent'];
$group[$k]['name'] = $value['name'];
$group[$k]['id'] = $value['id'];
}

Try this:
foreach($arr1 as $k=>$v) {
$arr1[$k]['parent'] = $arr2[$k]['parent'];
}
print_r( $arr1 );

Related

How to merge arrays based on value in php?

I am having 2 arrays and i have to merge that arrays with similar values. i tried for each and basic functions of php for array merging but not getting proper result.
i tried below thing but it wont work for me as i am having multiple data in second array. as you can see in child array i am having multiple records and i want to keep that together inside base array.
$base= [
['id' => 1],
['id' => 2],
['id' => 3],
['id' => 4],
];
$child = [
['id' => 1, 'size' => 'SM'],
['id' => 1, 'size' => 'LK'],
['id' => 2, 'size' => 'XL'],
['id' => 4, 'size' => 'LG'],
['id' => 3, 'size' => 'MD'],
];
foreach(array_merge($base, $child) as $el){
$merged[$el['id']] = ($merged[$el['id']] ?? []) + $el;
}
Output :
array (
1 =>
array (
'id' => 1,
'size' => 'SM',
),
2 =>
array (
'id' => 2,
'size' => 'XL',
),
3 =>
array (
'id' => 3,
'size' => 'MD',
),
4 =>
array (
'id' => 4,
'size' => 'LG',
),
)
desired output :
array (
1 =>
array (
'id' => 1,
1 => array('size' => 'SM'),
2 => array('size' => 'LK'),
),
2 =>
array (
'id' => 2,
1 => array('size' => 'XL'),
),
3 =>
array (
'id' => 3,
1 => array('size' => 'MD'),
),
4 =>
array (
'id' => 4,
1 => array('size' => 'LG'),
),
)
Because your array $child have same key id value, and every you save the array, it always destroyed old array with same key id.
Here the working code :
<?php
$base= [
['id' => 1],
['id' => 2],
['id' => 3],
['id' => 4],
];
$child = [
['id' => 1, 'size' => 'SM'],
['id' => 1, 'size' => 'LK'],
['id' => 2, 'size' => 'XL'],
['id' => 4, 'size' => 'LG'],
['id' => 3, 'size' => 'MD'],
];
foreach(array_merge($base, $child) as $el){
if(!isset($el['size'])){ // $base doesn't have 'size' key
$merged[$el['id']] = []; // fill with empty array
}else{
$merged[$el['id']][] = $el;
}
// bellow code is for start array index from 1 instead of 0
array_unshift($merged[$el['id']],"");
unset($merged[$el['id']][0]);
}
print_r($merged);

Check if key exist in array if so, count it and create a new array php

From my SQL query, I will get the following array as a result. This is the last result I can get from SQL.I cant change any SQL because of some constraint.
I need to check if the same id exists or not and if it does need to count them and remove one of the duplicate array having the same id.
Sample array is
$array = array(
0 => array(
'id' => '17',
'status' => 1,
),
1 => array(
'id' => '18',
'status' => 1,
),
2 => array(
'id' => '21',
'status' => 1,
),
3 => array(
'id' => '5',
'status' => 2,
),
4 => array(
'id' => '18',
'status' => 1,
),
5 => array(
'id' => '22',
'status' => 5,
),
6 => array(
'id' => '6',
'status' => 1,
),
);
I need to check if they have a duplicate id or not, if yes need to count them and remove one of the duplicates.We need to preserve the array structure.
End Results should be
array(
0 => array(
'id' => '17',
'status' => 1,
'count'=1,
),
1 => array(
'id' => '18',
'status' => 1,
'count'=2,
),
2 => array(
'id' => '21',
'status' => 1,
'count'=1,
),
3 => array(
'id' => '5',
'status' => 2,
'count'=1,
),
4 => array(
'id' => '22',
'status' => 5,
'count'=1,
),
5 => array(
'id' => '6',
'status' => 1,
'count'==>1,
),
)
You can Check it by this way but duplicate entry still in the array.
$ids = array();
foreach ($array as $key => $value)
{
$ids[] = $value['id'];
$count = array_count_values($ids);
}
for($i = 0; $i < count($array);$i++)
{
$array[$i]['count'] = $count[$array[$i]['id']];
}
You can do this with the array_unique function.
Use it like so:
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
Which outputs:
Array ( [a] => red [b] => green )

php usort() with order of precedence for json sorting

I need to sort a json array with key value pair in a certain order of precedence(specialcharacters > numbers > lower case > uppercase). I tried with ascii code but couldn't get as expected.
$arr1 = array (
0 =>
array (
'id' => 1,
'name' => 'B',
'value' => 'abc',
'order' => 6,
),
1 =>
array (
'id' => 2,
'name' => 'a',
'value' => 'xyz',
'order' => 2,
),
2 =>
array (
'id' => 3,
'name' => 'A',
'value' => 'ghi',
'order' => 1,
),
3 =>
array (
'id' => 4,
'name' => '123',
'value' => 'xyz',
'order' => 2,
),
4 =>
array (
'id' => 5,
'name' => 'd',
'value' => 'uvw',
'order' => 3,
),
5 =>
array (
'id' => 6,
'name' => '#2',
'value' => 'def',
'order' => 3,
),
);
function cmp($a, $b)
{
$at = iconv('UTF-8', 'ASCII//TRANSLIT', $a['name']);
$bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b['name']);
return strcmp($at, $bt);
}
usort($arr1, "cmp");
print_r($arr1);
Can anyone help me to resolve it?
<?php
// Obtain a list of columns
foreach ($arr1 as $key => $row) {
$arr1[$key] = $row['value'];
}
ksort($arr1);
?>

multidimensional array merge operation inside loop

let's say I have two arrays like so:
$array1 = array('A' => array(
'B' => array(
'C' => array(
'D' => array(
'data' => array(
0 => array(
'id' => 1,
'name' => 'name 1'),
1 => array(
'id' => 2,
'name' => 'name 2')))))));
$array2 = array('A' => array(
'B' => array(
'C' => array(
'E' => array(
'data' => array(
0 => array(
'id' => 3,
'name' => 'name 3'),
1 => array(
'id' => 4,
'name' => 'name 4')))))));
As you can see, the two arrays have the same key A, B, and C but the keys are different afterwards. How do I merge these two arrays into something like this:
$final_array = array('A' => array(
'B' => array(
'C' => array(
'D' => array(
'data' => array(
0 => array(
'id' => 1,
'name' => 'name 1'),
1 => array(
'id' => 2,
'name' => 'name 2'))),
'E' => array(
'data' => array(
0 => array(
'id' => 3,
'name' => 'name 3'),
1 => array(
'id' => 4,
'name' => 'name 4')))))));
As you can see, in this case I merge the arrays together into the same array that contains different keys for both. In order words, here I'm putting the array starting from key E from the second array into the array with index C.
Any help will be appreciated, thanks
EDIT: Now, how about if my arrays ($array1, $array2, $array3, $array4, etc...) are generated inside a foreach loop, how do I merge all of those arrays together (Notice that I do not know the number of arrays beforehand)
http://php.net/manual/en/function.array-merge-recursive.php
print_r(array_merge_recursive($array1, $array2));
This should do the trick.
Added:
$collection=array();
foreach() {
$collection[]=$myArray; //here you add your array to collection
}
print_r(call_user_func_array('array_merge_recursive', $collection));
i have not tested this but try this code:
foreach( $array1 as $key => $val )
{
if( !in_array( $key, $array2 ) )
{
$array2[$key] = $val;
}
}
EDIT
use Rok Kralj's answer, using native functions are probably the best way to do this as they are much faster.

Get all children for a given parent id in array

I have an array like this:
array(
array(
'id' => 1,
'parent_id' => null
),
array(
'id' => 2,
'parent_id' => 1
),
array(
'id' => 3,
'parent_id' => 2
),
array(
'id' => 4,
'parent_id' => null
),
array(
'id' => 5,
'parent_id' => 4
)
);
How can i find all the childrens of a given parent_id including all grand children? For example the function will return 2,3 for parent_id 1.
Thanks.
// I corrected the array to fit your result 1 => 2,3
<?php
$test = array(
array(
'id' => 1,
'parent_id' => null
),
array(
'id' => 2,
'parent_id' => 1
),
array(
'id' => 3,
'parent_id' => 1
),
array(
'id' => 4,
'parent_id' => null
),
array(
'id' => 5,
'parent_id' => 4
)
);
// 1_2+3
$parent_childs = ARRAY();
foreach ($test AS $index => $child) {
if (!isset($child['parent_id'])) { continue; }
$parent_childs[$child['parent_id']][] = $child['id'];
}
echo '<pre>';var_dump($parent_childs); echo '</pre>';
?>

Categories