Kobid Kunda
Kobid Kunda

Reputation: 47

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

Upvotes: 0

Views: 519

Answers (2)

Rwd
Rwd

Reputation: 35210

As an alternative to the accepted answer you could also use array_map.

array_map will essentially take one or more arrays and iterate over them by passing the current iteration of each array to the callback function:

$people = array_map(function ($fname, $lname, $age) {
    return [
        'fname' => $fname,
        'lname' => $lname,
        'age'   => $age,
    ];
}, $firstNames, $lastNames, $ages);

You could then make it even shorter by using compact

$people = array_map(function ($fname, $lname, $age) {
    return compact('fname', 'lname', 'age');
}, $firstNames, $lastNames, $ages);

Upvotes: 1

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12401

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.

Upvotes: 0

Related Questions