Array splice with key name

I have 2 arrays ($data_1 & $data_2) which have different value but have a relation, I want to merge those array, completely with key name

$data_1 = 
'[
    {
        "fruit": "apple",
        "weight": "15"
    },
    {
        "fruit": "durian",
        "weight": "50"
    },
    {
        "fruit": "orange",
        "weight": "10"
    }
]';


$data_2 =
'[
    {
        "color": "red",
        "thorn": "no"
    },
    {
        "color": "green",
        "thorn": "yes"
    },
    {
        "color": "orange",
        "thorn": "no"
    }
]';

but I want to combine those array, then I have a full data like this:

$full_data = 
'[
    {
        "fruit": "apple",
        "weight": "15",
        "color": "red",
        "thorn": "no"
    },
    {
        "fruit": "durian",
        "weight": "50",
        "color": "green",
        "thorn": "yes"
    },
    {
        "fruit": "orange",
        "weight": "10",
        "color": "orange",
        "thorn": "no"
    }
]';

I tried with array_splice()

for ($i=0; $i < count($data_2); $i++) { 
    array_splice($data_1[$i], 0, 0, $data_2[$i]);
}

but it returns with ‘0’ and ‘1’ not original key name…

'[
    {
        "fruit": "apple",
        "weight": "15",
        "0": "red",
        "1": "no"
    },
    {
        "fruit": "durian",
        "weight": "50",
        "0": "green",
        "1": "yes"
    },
    {
        "fruit": "orange",
        "weight": "10",
        "0": "orange",
        "1": "no"
    }
]';

I want to replace that ‘0’ and ‘1’ into the original key names

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use array_merge to merge two arrays.

$full_data = [];
for ($i=0; $i < count($data_2); $i++) { 
    $full_data[$i] = array_merge($data_1[$i], $data_2[$i]);
}

Method 2

Simply, you could do it by

  1. convert two arrays format json into two php arrays using json_decode function.
  2. iterate over one of them and fill $full_data with values of two arrays respectively.
  3. display the array with format json using json_encode function.
// 1.
$data1 = json_decode($data_1,true);
$data2 = json_decode($data_2,true);

// 2.
$full_data = [];
for ($i=0; $i < count($data1); $i++) { 
    $full_data[$i] = $data1[$i] + $data2[$i];
}
// 3. 
echo(json_encode($full_data));
/*
[
 {"fruit":"apple","weight":"15","color":"red","thorn":"no"},
 {"fruit":"durian","weight":"50","color":"green","thorn":"yes"},
 {"fruit":"orange","weight":"10","color":"orange","thorn":"no"}
]
*/


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x