dongxia026531
dongxia026531
2018-11-09 14:35

在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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • duandan5471 duandan5471 3年前

    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
    }
    
    点赞 评论 复制链接分享
  • dsa45664 dsa45664 3年前

    For example:

    $new_array = array_map(
        function ($v) { return [$v]; }, 
        ['A', 'B', 'C']
    );
    
    点赞 评论 复制链接分享
  • duanping2695 duanping2695 3年前
    $arrOld = ['A','B','C','D','E'];
    $arrNew = [];
    foreach($arrOld as $key => $value){
        $arrNew[] = [$key => $value];
    }
    
    点赞 评论 复制链接分享

相关推荐