PHP : How to make parallel arrays from multidimentional array - php

I have this type of array
$arr = array(
0 => array(
0 => array(
'name' => 'test1',
'country' => 'abc'
)
1 => array(
'name' => 'test2',
'country' => 'xyz'
)
)
1 => array(
'name' => 'test3',
'country' => 'pqr'
)
);
How can I make all arrays as parallel arrays. So that all sub arrays are parallel to each other without using any loop.
Like this
$arr = array(
0 => array(
'name' => 'test1',
'country' => 'abc'
)
1 => array(
'name' => 'test2',
'country' => 'xyz'
)
2 => array(
'name' => 'test3',
'country' => 'pqr'
)
);
Any help is much appreciated. !

A dynamic version of Nigel's code would be to loop the array and merge each subarray.
$new = [];
foreach($arr as $subarr){
$new = array_merge($new, $subarr);
}
var_dump($new);
https://3v4l.org/np2ZD

You could simply merge the arrays...
$out = array_merge($arr[0], [$arr[1]]);
print_r($out);
Which gives...
Array
(
[0] => Array
(
[name] => test1
[country] => abc
)
[1] => Array
(
[name] => test2
[country] => xyz
)
[2] => Array
(
[name] => test3
[country] => pqr
)
)

Related

I want a particular format array from an array in PHP

I want to modify the existing array to a particular format please see the below array what i have and what i want
I have array as :
Array
(
[0] => Array
(
[block_id] => 1
[title] => Test1
[identifier] => test1
[content] => some test data
[creation_time] => 2019-09-03 09:47:35
[update_time] => 2019-09-03 09:47:35
[is_active] => 1
)
[1] => Array
(
[block_id] => 2
[title] => test2
[identifier] => twst2
[content] => dfdsffsdfsdfsfsdf
[creation_time] => 2019-09-03 09:48:03
[update_time] => 2019-09-03 09:48:03
[is_active] => 1
)
)
And I want this array as :
$options = [
['value' => 'test1', 'label' => __('Test1')],
['value' => 'test2', 'label' => __('Test2')],
['value' => 'test3', 'label' => __('Test3')],
['value' => 'test4', 'label' => __('Test4')],
['value' => 'test5', 'label' => __('Test5')],
['value' => 'test6', 'label' => __('Test6')]
];
Try this Solution.
$data = Array ( Array
(
'block_id' => 1,
'title' => 'Test1'
), Array
(
'block_id' => 2,
'title' => 'test2'
)
);
foreach($data as $k => $val){
$options[$k]['value'] = $val['title'];
$options[$k]['label'] = '__("'.ucfirst($val['title']).'")';
}
echo "<pre>";
print_r( $options);
Expected Result is
Array
(
[0] => Array
(
[value] => Test1
[label] => __("Test1")
)
[1] => Array
(
[value] => test2
[label] => __("Test2")
)
)
If $array is your array, then
foreach ($array as $k => $v)
{
$options[] = [ 'value' => $v['identifier'], 'label' => "__('" . $v['title'] . "')"];
}
If you are trying "to modify the existing array to a particular format" , next approach may help. When you precede $value with &, the $value will be assigned by reference and you can directly modify it.
<?php
foreach($array as &$value) {
$value = array(
'value' => $value["identifier"],
'label' => "__('".$value["title"]."')"
);
};
unset($value);
?>
Try this Solution.
foreach ($array as $k => $val)
{
$options[] = [ 'val' => $val['identifier'], 'label' => "__('" . $val['title'] . "')"];
}

PHP - Merge 2 multidimensional array based on value

Currently, I have 2 multidimensional array and I'm looking to combine them into one giant array where the value's name in array 1 matches the value's name in array 2.
The array's look as followed...
Array1
(
[0] => Array
(
[id] => 1
[name] => test1
[desc] => test_desc
[quantity] => 3
)
[1] => Array
(
[id] => 2
[name] => test2
[desc] => test_desc
[quantity] => 33
)
)
Array2
(
[0] => Array
(
[holder] => 'John'
[name] => test1
[desc] => test_desc
[location] => ATL
)
[1] => Array
(
[holder] => 'Jackie'
[name] => test3
[desc] => test_desc
[location] => SF
)
)
I'm looking to merge the arrays where the 'name' column in array1 matches in array2 and also combine the columns in array's 1 & 2 into the final array. This should look like...
FinalArray
(
[0] => Array
(
[id] => 1
[holder] => 'John'
[name] => test1
[desc] => test_desc
[location] => ATL
[quantity] => 3
)
[1] => Array
(
[holder] => 'Jackie'
[name] => test3
[desc] => test_desc
[location] => SF
)
[2] => Array
(
[id] => 2
[name] => test2
[desc] => test_desc
[quantity] => 33
)
)
Where the "test1" combines the different columns across the 2 arrays into a new array inside the "FinalArray". I've tried researching some ideas with array_merge and array_merge_recursive but I'm not entirely sure if I'm going in the correct direction. Thanks in advance.
Try like this
$array1=[['id' => 1,'name' => 'test1','desc' => 'test_desc','quantity' => 3],
['id' => 2,'name' => 'test2','desc' => 'test_desc','quantity' => 33]];
$array2=[['holder' => 'John','name' => 'test1','desc' => 'test_desc','location' => 'ATL'],
['holder' => 'Jackie','name' => 'test3','desc' => 'test_desc','location' => 'SF']];
$final=[];
foreach ($array1 as $key1=>$data1){
foreach ($array2 as $key2=>$data2){
if($data1['name']==$data2['name']){
$final[]=$data1+$data2;
unset($array1[$key1]);
unset($array2[$key2]);
}
}
}
if(!empty($array1)){
foreach ($array1 as $value){
$final[]=$value;
}
}
if(!empty($array2)){
foreach ($array2 as $value){
$final[]=$value;
}
}
It will give output as
One more solution
function merge_by_name(array $arr1, array $arr2) {
$result = [];
foreach ($arr1 as $value) {
$key = array_search($value['name'], array_column($arr2, 'name'));
if($key !== false) {
$result[] = array_merge($value, $arr2[$key]);
unset($arr2[$key]);
} else {
$result[] = $value;
}
}
$result = array_merge($result, $arr2);
return $result;
}
Test
$arr1 = [
[
'id' => 1,
'name' => 'test1',
'desc' => 'test_desc',
'quantity' => 3
],
[
'id' => 2,
'name' => 'test2',
'desc' => 'test_desc',
'quantity' => 33
],
];
$arr2 = [
[
'holder' => 'John',
'name' => 'test1',
'desc' => 'test_desc',
'location' => 'ATL'
],
[
'holder' => 'Jackie',
'name' => 'test3',
'desc' => 'test_desc',
'location' => 'SF'
],
];
var_export(merge_by_name($arr1, $arr2));
Result
array (
0 =>
array (
'id' => 1,
'name' => 'test1',
'desc' => 'test_desc',
'quantity' => 3,
'holder' => 'John',
'location' => 'ATL',
),
1 =>
array (
'id' => 2,
'name' => 'test2',
'desc' => 'test_desc',
'quantity' => 33,
),
2 =>
array (
'holder' => 'Jackie',
'name' => 'test3',
'desc' => 'test_desc',
'location' => 'SF',
),
)

How to flatten (compress) multi-dimensional array into one-dimensional array in PHP?

I got this array. I want all the other 3 array come into this [0] => Array. Don't want unique value just want to merge all array flat in to [0] => Array.
Array
(
[0] => Array
(
[0] => Array
(
[Campaign] => xxx
[Phone] => 111
[State] => cd
)
)
[1] => Array
(
[0] => Array
(
[Campaign] => zxxxzx
[Phone] => 111111
[State] => zxxx
)
)
[2] => Array
(
[0] => Array
(
[Campaign] => aaaa
[Phone] => 111
[State] => Csd
)
)
[3] => Array
(
[0] => Array
(
[Campaign] => sasa
[Phone] => 111
[State] => asas
)
)
)
This is another example of how important the naming is. What you are working with is basically:
$recordsGroups = array(
// first group:
array(
// record 1:
array(
'key1' => 'val1',
'key2' => 'val2',
),
// record 2:
array(
'key1' => 'aaa',
'key2' => 'bbb',
),
),
// 2nd group:
array(
// record 3:
array(
'key1' => 'ccc',
'key2' => 'ddd',
),
),
);
And what you are probably trying to do is:
$records = array();
foreach ($recordsGroups as $group)
foreach ($group as $record)
$records[] = $record;
Which will give you:
$records = array(
// record 1:
array(
'key1' => 'val1',
'key2' => 'val2',
),
// record 2:
array(
'key1' => 'aaa',
'key2' => 'bbb',
),
// record 3:
array(
'key1' => 'ccc',
'key2' => 'ddd',
),
);
This should do nicely:
$array = call_user_func_array('array_merge', $array);
Or Argument unpacking via ... (splat operator):
$array = array_merge(...$array);
Because arrays can't have duplicate keys, the best that this multi-dim array can be condensed is down to an indexed array of associative arrays. array_column() will make quick work of this task.
Code: (Demo)
$array=[
[
['Campaign'=>'xxx','Phone'=>'111','State'=>'cd']
],
[
['Campaign'=>'zxxxzx','Phone'=>'111111','State'=>'zxxx']
],
[
['Campaign'=>'aaaa','Phone'=>'111','State'=>'Csd']
],
[
['Campaign'=>'sasa','Phone'=>'111','State'=>'asas']
]
];
var_export(array_column($array,0));
Output:
array (
0 =>
array (
'Campaign' => 'xxx',
'Phone' => '111',
'State' => 'cd',
),
1 =>
array (
'Campaign' => 'zxxxzx',
'Phone' => '111111',
'State' => 'zxxx',
),
2 =>
array (
'Campaign' => 'aaaa',
'Phone' => '111',
'State' => 'Csd',
),
3 =>
array (
'Campaign' => 'sasa',
'Phone' => '111',
'State' => 'asas',
),
)

PHP Replace Array Values

I have 2 multidimensional arrays that I am working with:
$arr1 =
Array
([type] => characters
[version] => 5.6.7.8
[data] => Array
([Char1] => Array
([id] => 1
[name] =>Char1
[title] =>Example
[tags] => Array
([0] => DPS
[1] => Support))
[Char2] => Array
([id] => 2
[name] =>Char2
[title] =>Example
[tags] => Array
([0] => Tank
[1] => N/A)
)
)
etc...
$arr2=
Array
([games] => Array
([gameId] => 123
[gameType => Match
[char_id] => 1
[stats] => Array
([damage] => 55555
[kills] => 5)
)
([gameId] => 157
[gameType => Match
[char_id] => 2
[stats] => Array
([damage] => 12642
[kills] => 9)
)
etc...
Basically, I need almost all the data in $arr2... but only the Char name from $arr1. How could I merge or add the $arr1['name'] key=>value into $arr2 where $arr1['id'] is equal to $arr2['char_id'] as the "id" field of each array is the same number.
I've attempted using array_merge and array_replace, but I haven't come up with any working solutions. This is also all data that I am receiving from a 3rd party, so I have no control on initial array setup.
Thanks for any help or suggestions!
Actually, this is quite straighforward. (I don't think there a built-in function that does this.)
Loop $arr2 and under it loop also $arr1. While under loop, just add a condition that if both ID's match, add that particular name to $arr2. (And use some referencing & on $arr2)
Consider this example:
// your data
$arr1 = array(
'type' => 'characters',
'version' => '5.6.7.8',
'data' => array(
'Char1' => array(
'id' => 1,
'name' => 'Char1',
'title' => 'Example',
'tags' => array('DPS', 'Support'),
),
'Char2' => array(
'id' => 2,
'name' => 'Char2',
'title' => 'Example',
'tags' => array('Tank', 'N/A'),
),
),
);
$arr2 = array(
'games' => array(
array(
'gameId' => 123,
'gameType' => 'Match',
'char_id' => 1,
'stats' => array('damage' => 55555, 'kills' => 5),
),
array(
'gameId' => 157,
'gameType' => 'Match',
'char_id' => 2,
'stats' => array('damage' => 12642, 'kills' => 9),
),
),
);
foreach($arr2['games'] as &$value) {
$arr2_char_id = $value['char_id'];
// loop and check against the $arr1
foreach($arr1['data'] as $element) {
if($arr2_char_id == $element['id']) {
$value['name'] = $element['name'];
}
}
}
echo '<pre>';
print_r($arr2);
$arr2 should look now like this:
Array
(
[games] => Array
(
[0] => Array
(
[gameId] => 123
[gameType] => Match
[char_id] => 1
[stats] => Array
(
[damage] => 55555
[kills] => 5
)
[name] => Char1 // <-- name
)
[1] => Array
(
[gameId] => 157
[gameType] => Match
[char_id] => 2
[stats] => Array
(
[damage] => 12642
[kills] => 9
)
[name] => Char2 // <-- name
)
)
)
Iterate over $arr2 and add the data to it from the matching $arr1 array value:
$i = 0;
foreach($arr2['games'] as $arr2Game){
$id = $arr2Game['char_id'];
$arr2['games'][$i]['name'] = $arr1['data'][$id]['name'];
$i++;
}
Have not tested this code.
If I'm understanding you correctly, you want to add a name index to each of the arrays within the $arr2['games'] array.
foreach($arr2['games'] as $key => $innerArray)
{
$arr2['games'][$key]['name'] = $arr1['data']['Char'.$innerArray['char_id']]['name'];
}

How do I make a list of specific values in a PHP multidimensional array?

I have a multidimensional array like so:
$neighborhood => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
)
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
);
I would like to create another array (let's call it $array_of_moms) of all the moms in the neighborhood. Pulling them all in separately is doable, but not practical (like so):
$array_of_moms = array(
$neighborhood['the_smiths']['mom'],
$neighborhood['the_acostas']['mom'],
)
How do I create something like this:
$array_of_moms = $neighborhood['mom'];
$moms = array();
foreach($neighborhood as $family)
{
$moms[] = $family['mom'];
}
This'll iterate through each family in the array and add the mom to the new $moms array.
Using foreach, you can iterate through an array with variable indicies.
$array_of_moms = array();
foreach ($neighborhood AS $family) {
$array_of_moms[] = $family['mom']; // append mom of each family to array
}
If you can manipulate your array, you could:
<?php
$neighborhood = array(
'families' => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
),
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
)
);
foreach ($neighborhood['families'] as $family => $folks) {
$neighborhood['moms'][] = $folks['mom'];
}
print_r($neighborhood);
?>
Which outputs:
Array
(
[families] => Array
(
[the_smiths] => Array
(
[dad] => Donald
[mom] => Mary
[daughter] => Donna
[son] => Samuel
)
[the_acostas] => Array
(
[dad] => Diego
[mom] => Marcela
[daughter] => Dominga
[son] => Sergio
)
)
[moms] => Array
(
[0] => Mary
[1] => Marcela
)
)
http://codepad.org/xbnj5UmV

Categories