How to merge two nested associative array with same indexes? [duplicate] - php

This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 4 months ago.
I have two arrays with same indexes, and unfortunately array_merge_recursive doesn't work for me.
First array is like this:
$firstarray = array(
0 => array('id' => 1, 'name' => 'John Smith'),
1 => array('id' => 2, 'name' => 'Jane Doe')
);
Where second array is:
$secondarray = array(
0 => array('email' => 'john#smith.com'),
1 => array('email' => 'jane#doe.com')
);
Desired output would be like this,
Array
(
[0] => Array
(
[id] => 1
[name] => John Smith
[email] => john#smith.com
)
[1] => Array
(
[id] => 2
[name] => Jane Doe
[email] => jane#doe.com
)
)
But I am getting second array items appended to original array like this:
Array
(
[0] => Array
(
[id] => 1
[name] => John Smith
)
[1] => Array
(
[id] => 2
[name] => Jane Doe
)
[2] => Array
(
[email] => john#smith.com
)
[3] => Array
(
[email] => jane#doe.com
)
)

for($i = 0; $i<count($firstarray); $i++){
$output[] = array_merge($firstarray[$i],$secondarray[$i]);
}
You can the above mentioned code or you can use array_map() & array_merge().
Like:
$output = array_map('array_merge', $firstarray, $secondarray);

You guys sure go the complicated way :)
$mergedarray = array_map('array_merge', $firstarray, $secondarray);
Basically "merge the arrays of each index".
array_merge_recursive doesn't work because number index are not considered as associative key. So it just push the value instead of merging them.

Try this:
$firstarray = array(
0 => array('id' => 1, 'name' => 'John Smith'),
1 => array('id' => 2, 'name' => 'Jane Doe')
);
$secondarray = array(
0 => array('email' => 'john#smith.com'),
1 => array('email' => 'jane#doe.com')
);
foreach($firstarray as $key1 => $value1)
{
foreach($secondarray as $key2 => $value2)
{
if($key1 == $key2)
{
$firstarray[$key1]["email"] = $value2["email"];
}
}
}
print_r($firstarray);

Try below code:-
$firstarray = array(
0 => array('id' => 1, 'name' => 'John Smith'),
1 => array('id' => 2, 'name' => 'Jane Doe')
);
$secondarray = array(
0 => array('email' => 'john#smith.com'),
1 => array('email' => 'jane#doe.com')
);
Use simple foreach loop
$res = [];
foreach($firstarray as $k=>$record){
$record['email'] = $secondarray[$k]['email'];
$res[] = $record;
}
echo '<pre>'; print_r($res);
OR use array_map() function
$res = array_map(function($a,$b){
return ['id'=>$a['id'],'name'=>$a['name'],'email'=>$b['email']];
},$firstarray,$secondarray);
echo '<pre>'; print_r($res);

Related

Convert 2d array by specified 2d format

I need to convert the below 2d array in to specified 2d array format. Array contains multiple parent and multiple child array. Also, have tried to convert the code, but am not getting the expected output.
This is the code what i have tried,
$a1 = array(
'0' =>
array(
'banner_details' =>
array(
'id' => 2,
'section_id' => 24
),
'slide_details' =>
array(
0 => array(
'id' => 74,
'name' => 'Ads1'
),
1 => array(
'id' => 2,
'name' => 'Ads2'
)
)
),
'1' =>
array(
'banner_details' =>
array(
'id' => 106,
'section_id' => 92
),
'slide_details' =>
array(
0 => array(
'id' => 2001,
'name' => 'Adv1'
),
1 => array(
'id' => 2002,
'name' => 'Adv2'
)
)
)
);
$s = [];
for($i = 0; $i<2; $i++) {
foreach($a1[$i]['slide_details'] as $vs){
$s[] = $vs;
}
}
My output:
Array
(
[0] => Array
(
[id] => 74
[name] => Ads1
)
[1] => Array
(
[id] => 2
[name] => Ads2
)
[2] => Array
(
[id] => 2001
[name] => Adv1
)
[3] => Array
(
[id] => 2002
[name] => Adv2
)
)
Expected output:
Array
(
[24] => Array
(
[0] => 74
[1] => 2
)
[92] => Array
(
[0] => 2001
[1] => 2002
)
)
please check the above code and let me know.
Thanks,
You can apply next simple foreach loop with help of isset() function:
foreach($a1 as $data){
if (isset($data['banner_details']['section_id'])){
$s[$data['banner_details']['section_id']] = [];
if (isset($data['slide_details'])){
foreach($data['slide_details'] as $row){
$s[$data['banner_details']['section_id']][] = $row['id'];
}
}
}
}
Demo
If you know that indexes like banner_details or slide_details or section_id will be there always then you can skip isset() in if statements.
You can use array_column function for simple solution:
$result = [];
foreach ($a1 as $item)
{
$result[$item['banner_details']['section_id']] = array_column($item['slide_details'], 'id');
}
var_dump($result);

shift multidimentional array to single array

I want to remove key 0 from parent array and set child array as parent.
Here I will get single value so one array is ok for me.
My current array looks like this
Array
(
[0] => Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
)
I want it like below. expected result
Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
For this I tried like below but no success.
$new = array();
foreach ($data as $v){
$new = array_merge($new , array_values($v)) ;
}
but in my code it's removed key e.g id,api_key, etc....
I need key name also in my new array. please suggest
Remove the array_values
Solution
<?php
$test = array(
array
(
'id' => 3,
'api_key' => 'acount266'
)
);
$new = array();
foreach($test as $v){
$new = array_merge($new, $v);
}
var_dump($new);
Result
array(2) {
["id"]=>
int(3)
["api_key"]=>
string(9) "acount266"
}
According to documentation of PHP as mentioned
reset() function returns the value of the first array element, or
FALSE if the array is empty.
$array = array(
array(
'id' => 3,
'api_key' => 'acount266',
'auth_domain' => 'Tester26',
'database_url' => 'vcc.test.acc+27#gmail.com',
'project_id' => '12345',
'storage_bucket' => '',
'secret_key_path' => '',
'fcm_server_key' => 1,
'messaging_sender_id' => 0,
'key_phrase' => '',
'disable' => 0,
'created' => '',
'updated' => ''
)
);
print_r(reset($test));
I tried this:
$arr = array();
foreach ($examples as $example) {
foreach ($example as $e) {
array_push($arr, $e);
}
}
Don't overcomplicate this, reassigning the first element to the parent array is quick and easy:
<?php
$array =
array (
0 =>
array (
'first' => 'Michael',
'last' => 'Thompson'
)
);
$array = $array[0];
var_export($array);
Output:
array (
'first' => 'Michael',
'last' => 'Thompson',
)
Or:
$array = array_shift($array);

How to convert an array to an indexed array

I try to convert an array to an indexed array but none of the array functions I found can solve my problem
I have this array
Array(
[no_discount] => 0
[manufacturers_id] => 2
[id] => 3
)
Array(
[no_discount] => 1
[manufacturers_id] => 1
[id] => 1
)
and I would like to convert this array to
Array(
[0] => Array(
[no_discount] => 0
[manufacturers_id] => 2
[id] => 3
)
[1] => Array(
[no_discount] => 1
[manufacturers_id] => 1
[id] => 1
)
)
Is there a simple array function or do I have use a loop?
loop - or write you own ..
$tgt = [];
foreach ( $src as $t) { $tgt[] = $t; }
I'm not sure how you are getting your array but will this work for you?
$main_array = array();
$one = Array(
"no_discount" => 0,
"manufacturers_id" => 2,
"id" => 3,
);
$two = Array(
"no_discount" => 1,
"manufacturers_id" => 1,
"id" => 1,
);
array_push($main_array, $one);
array_push($main_array, $two);
print_r($main_array);

Rearrange array

I am getting this array when form is submitted
array
'item' =>
array
0 => string 'Salt'
1 => string 'Pepper'
'quantity' =>
array (size=2)
0 => string '2 spoon'
1 => string '5'
and now want to rearrange above array, so it should look like
array
'0' =>
array
'item' => string 'Salt'
'quantity' => string '2 spoon'
'1' =>
array
'item' => string 'Pepper'
'quantity' => string '5'
I tried so many combinations but failed, will somebody help me how to rearrange this array. Any help will be more than appreciated.
Try this
$array = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$new_array = array();
foreach ($array['item'] as $key => $value) {
$new_array[$key]["item"] = $value;
$new_array[$key]["quantity"] = $array['quantity'][$key];
}
echo "<pre>";
var_dump($new_array);
Do it as below -
<?php
$arr=array(
'item' =>
array(
0 => 'Salt' ,
1 => 'Pepper'
),
'quantity' =>
array (
0 =>'spoon',
1 =>'5'
)
);
$result=array();
$com=array_combine($arr['item'],$arr['quantity']);
foreach($com as $k=>$v)
{
$result[]=array("item"=>$k,"quantity"=>$v);
}
print_r($result);
?>
OUTPUT
Array (
[0] => Array ( [item] => Salt [quantity] => spoon )
[1] => Array ( [item] => Pepper [quantity] => 5 )
)
try this, I think this would help you,
$a = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$i = 0;
foreach($a['item'] as $row){
$b[$i]["item"] = $row;
$b[$i]["quantity"] = $a['quantity'][$i];
$i++;
}
print_r($b);
Output from print_r() will be
Array
(
[0] => Array
(
[item] => Salt
[quantity] => 2 spoon
)
[1] => Array
(
[item] => Pepper
[quantity] => 5
)
)
You can simply use array_walk like as
$result = [];
array_walk($arr['item'], function($v, $k)use(&$result, $arr) {
$result[$k]['item'] = $arr['item'][$k];
$result[$k]['quantity'] = $arr['quantity'][$k];
});
print_r($result);
Demo
Hoping that your array is stored in the $array variable and that item is leading. Meaning that there is always an item in the array and not always a quantity
<?php
foreach($array['item'] as $key => $item) {
$newArray[$key]['item'] = $item;
if (isset($array['quantity'][$key]) {
$newArray[$key]['quantity'] = $array['quantity'][$key];
} else {
$newArray[$key]['quantity'] = 0;
}
?>

How to match key value in two arrays in php [duplicate]

This question already has answers here:
Find intersecting rows between two 2d arrays comparing differently keyed columns
(3 answers)
Closed 4 months ago.
I have two arrays
Array
(
[0] => Array
(
[id] => 1
[affiliate_id] => 190
)
[1] => Array
(
[id] => 2
[affiliate_id] => 946
)
)
Array
(
[0] => Array
(
[id] => 1
[user_id] => 190
)
[1] => Array
(
[id] => 2
[user_id] => 246
)
[2] => Array
(
[id] => 3
[user_id] => 249
)
[3] => Array
(
[id] => 3
[user_id] => 250
)
)
Now i want to get an array which has value like this
if affiliate_id of first array exists in second array as user_id then i will get its value in third array like
Array
(
[0] => Array
(
[affiliate_id] => 190
)
)
i just want affiliate_id which is exists in second array as user_id
$a = Array(
Array('id' => 1, 'affiliate_id' => 190),
Array('id' => 2, 'affiliate_id' => 946)
);
$b = Array(
Array('id' => 1, 'user_id' => 190),
Array('id' => 2, 'user_id' => 246),
Array('id' => 3, 'user_id' => 249),
Array('id' => 3, 'user_id' => 250)
);
$c = array_map(function ($arr) { return $arr['affiliate_id']; }, $a);
$d = array_map(function ($arr) { return $arr['user_id']; }, $b);
$e = array_intersect($c, $d);
print_r($e);
try in_array() with loop
$a = firstarray;
$b = second array;
$i =0;
foreach($b as $k=>$v) {
if(!empty($a[$i])) {
if(in_array($v['user_id'], $a[$i])) {
$c[]['affiliate_id'] = $v['user_id'];
}
}
$i++;
}
print_r($c);
output :-
Array
(
[0] => Array
(
[affiliate_id] => 190
)
)
Use the following code:
<?php
$arr1 = array(array('id' => 1, 'affiliate_id' => 190),
array('id' => 2, 'affiliate_id' => 946));
$arr2 = array(array('id' => 1, 'user_id' => 190),
array('id' => 2, 'user_id' => 246),
array('id' => 3, 'user_id' => 249),
array('id' => 4, 'user_id' => 250));
$count = 0;
foreach ($arr1 as $k1 => $v1) {
if (in_array($v1['affiliate_id'], $arr2[$count]))
{
$arr3[]['affiliate_id'] = $v1['affiliate_id'];
}
$count++;
}
echo '<pre>'; print_r($arr3);
Output
Array
(
[0] => Array
(
[affiliate_id] => 190
)
)

Categories