0

i have multiple array like this

$data1 = [1,2,3];
$data2 = [a,b,c];
$data3 = [x,y,z];

and i want to join them all into multiple array like this

$data = [
  1 => ['data2' => a, 'data3' => x],
  2 => ['data2' => b, 'data3' => y],
  3 => ['data2' => c, 'data3' => z]
];

i'm trying for loop but have no idea how to make it.

$data = [];
    for ($i=0; $i < count($desa); $i++) {
      $data[] .= array ($desa[$i] => [
        'info' => $info[$i],
        'link' => $link[$i],
        'sos' => $sos[$i],
        'eko' => $eko[$i]
      ]);
    }

    return $data;

can someone help me with this i'm using php

1 Answer 1

1

You can access the key-value pair individually in the foreach loop.

// initalize the required output array
$data = [];

// loop over the data1
foreach ($data1 as $key => $value) {

  // fill the output - key from loop will be used to 
  // access the values in data2 and data3
  $data[$value] = array('data2' => $data2[$key], 
                        'data3' => $data3[$key]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

ohh tanks mate u save my day (:
@AndiHaidar happy to help :)
wait for 2 minutes to vote right answer but i'll make it thanks
seems you have a typo. Should be $data[$value] not $data[value]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.