Skip to content
Advertisement

How insert Multiple Array item into One Array in PHP

i want to add multiple Array item into One Array Object in PHP

i have array like below :

    [
        {
            "name": "AAA"
        },
        {
            "family": "BBB"
        },
        {
            "job": "CCC"
        }
    ]

And i need to Convert like below:

{
    "name": "AAA",
    "family": "BBB",
    "job": "CCC"
}

Array Data maybe changed , but , i write this code for explain my problem :

$RetArray=array();
    $Array_Test=array(array('name'=>'AAA'),array('family'=>'BBB'),array('job'=>'CCC'));
    foreach ($Array_Test as $json_item){
       foreach ($json_item as $key=>$value){
       array_push($RetArray,array($key => $value));
     }
    }
    echo json_encode($RetArray);

But this code returns the same as the first array! I want to return every item into one array.

Advertisement

Answer

Try this:

$RetArray=[];
$SrcArray=[
    ["name"=>"AAA"],
    ["family"=>"BBB"],
    ["job"=>"CCC"],
];
foreach($SrcArray as $item){
    $RetArray=array_merge($RetArray,$item);
}
echo json_encode($RetArray);

Here is what it got: https://3v4l.org/kZJ2T

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement