0

Is there a simple php function to transform a simple array to multidimensional one with same key ?

For now I use :

 $array = [1, 4, 6];
 $arrayMulti = [];

 foreach ($array as $row) {
      $arrayMulti []= [
        'foreign_id' => $row,
      ];
 }

1 Answer 1

2

Yes you can do that using array_map

$array = [1, 4, 6]; 
$array = array_map(function ($a) { return array('foriegn_id'=>$a); }, $array);
print_r($array);

output

Array
(
    [0] => Array
        (
            [foriegn_id] => 1
        )

    [1] => Array
        (
            [foriegn_id] => 4
        )

    [2] => Array
        (
            [foriegn_id] => 6
        )

)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes one line is better, I thought a function existed like array_transform ) thanks

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.