Home > database >  How insert Multiple Array item into One Array in PHP
How insert Multiple Array item into One Array in PHP

Time:12-08

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.

CodePudding user response:

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

CodePudding user response:

you can use array_merge() or array_push()

  • Related