0

I have two arrays, looks like following

$array1 = array("color" => "red","size" => "32");
$array2 = array("color" => "blue","width" => "40");

and my php code is as follows

    <?php
        $array1 = array("color" => "red","size" => "32");
        $array2 = array("color" => "blue","width" => "40");
        $result = array_merge_recursive($array1, $array2);
        echo json_encode($result);
?>

The output of this code is

{
color: [
"red",
"blue"
],
size: "32",
width: "40"
}

I want to get output like

{
color: [
"red",
"blue"
],
size: [
"32",
""
],
width: [
"",
"40"
]
}

How I can get this ? Please help me quickly.

Thanks in advance.

2 Answers 2

1

Use array_merge with an array of default values

$array1 = array("color" => "red","size" => "32");
$array2 = array("color" => "blue","width" => "40");
$arrayInit = array("color" => "","width" => "","size"=>"");
$array1 = array_merge($arrayInit,$array1);
$array2 = array_merge($arrayInit,$array2);
$result = array_merge_recursive($array1, $array2);
echo json_encode($result);
Sign up to request clarification or add additional context in comments.

Comments

1
$keys = array_keys(array_merge($array1, $array2)); // get all the keys
foreach ($keys as $key) {
    // set each key in the result array to the value from the input array or a default ''
    $result[$key][] = isset($array1[$key]) ? $array1[$key] : '';
    $result[$key][] = isset($array2[$key]) ? $array2[$key] : '';
}
echo json_encode($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.