Skip to content
Advertisement

Merge multiple array in php laravel

Let us say I have a set of data of the first name

first name : `{ "abc","bvd","jhhg", "jju","jju"}`
Last name : `{ "hhh","uuu","tre", "vvg","yyy"}`
Age : `{ "44","33","34", "34,"65"}`

I want the result to return as

{
"fname" : "abc",
"lname" : "hhh",
"age" : "44"
},
{
"fname" : "bvd",
"lname" : "uuu",
"age" : "33"
},
{
"fname" : "jhhg",
"lname" : "tre",
"age" : "34"
}

How to do it in php / laravel

I have achieved the result but the response is too slow

  $cart = array();

   for($i = 1;$i<=($qty);$i++)
   {

       $fnames = CreateFirstName::all()->random(1);

       $fname = ($fnames[0]->fname);

       $images = CreateImageName::all()->random(1);

       $image = ($images[0]->imagelocation);


       $lnames = CreateLastName::all()->random(1);
       $lname = ($lnames[0]->lname);

       $cart[] = [
           'id' => $images[0]->id,
           'fname' => mb_substr($fname, 0, 10),
           'lname' => mb_substr($lname, 0, 10),
           'age' => rand(18,43),
           'city' => $region_name,
           'image' => $image

       ];

   }


   $collection = collect($cart);

image

The response is coming more than 20000 ms on the server or local enviroment

Advertisement

Answer

I assume the size of all the 3 arrays is same

$finalArray = array();
for($i=0;$i<count($firstArray);$i++){
    $finalArray[] = array("fname"=>$firstArray[$i], "lname"=>$lastArray[$i],"age"=>$ageArray[$i]);
} 

$finalArray has what you have.

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