简体   繁体   中英

Convert index array into multidimensional associative/index array in php

My array looks like this

Array
(
    [0] => A
    [1] => B
    [2] => C
)

Desired array

Array
(
    [0] => Array
        (
            [0] => A
        )

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

    [2] => Array
        (
            [0] => C
        )
)

I have gone through these links but didn't able to figure out the solution being a newbie.

Convert associative array into indexed

convert indexed multidimensional array to associative multidimensional array

For example:

$new_array = array_map(
    function ($v) { return [$v]; }, 
    ['A', 'B', 'C']
);
$arrOld = ['A','B','C','D','E'];
$arrNew = [];
foreach($arrOld as $key => $value){
    $arrNew[] = [$key => $value];
}

This is a blanket statement on how to get your desired array :

$desired_array = array(array("0"=>"A"), array("0"=>"B"), array("0"=>"C"));

However, dynamically, you could do the following :

//Assume $original_array = array("0"=>"A", "1"=>"B", "2"=>"C");

$desired_array = array(); // New Array
for($i = 0; $i < count($original_array); $i++){ // Loop over all elements in original array
array_push($desired_array, array("0"=>$original_array[$i])); // Place each valueable as an array in new desired array
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM