Karthiga Karthiga - 1 month ago 5
PHP Question

Using php display one array contain the key with the values that contain another array

Display one array with key and the value should be another array(key and value)

Example:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
?>

<pre><?php print_r($a1); ?></pre>
<pre><?php print_r($a2); ?></pre>


In the above example I want to display the array (a2) should be displayed in the value of array(a1) with the key "a".

Can anyone help?

Answer

It is unclear what you actually ask, but I would give this answer as a "long shot":

<?php
$a1 = ["a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow"];
$a2 = ["e"=>"red", "f"=>"green", "g"=>"blue"];
$a1["a"] = $a2;
?>
<pre><?php print_r($a1); ?></pre>

You obviously can shorten this into a more direct and readable style:

<?php
$a1 = [
    "a" => [
        "e"=>"red", 
        "f"=>"green", 
        "g"=>"blue"
    ], 
    "b" => "green", 
    "c" => "blue", 
    "d" => "yellow"
];
<pre><?php print_r($a1); ?></pre>

As it turned out in the confusing discussion in the comments below you are actually looking for a way to implode that second array into a comma separated list, so a single string... Here is a solution for that:

<?php
$a1 = ["a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow"];
$a2 = ["e"=>"red", "f"=>"green", "g"=>"blue"];
$a1["a"] = implode(',', $a2);
?>
<pre><?php print_r($a1); ?></pre>