【问题标题】:is it possible to convert associative array to multidimensional array?是否可以将关联数组转换为多维数组?
【发布时间】:2018-12-25 01:28:05
【问题描述】:

我有一个格式如下的表单域。

echo '<pre>';
print_r($_REQUEST);
echo '</pre>';exit;

[customer_id] = [0=> 4,1=>5];
[hobies]=>[0=> circket,1=>chess];

这里我要转换成多维关联数组。

$output  = [
4=>[
'hobies'=>'circket'
],
5=>[
'hobies'=> 'chess'
]
];

【问题讨论】:

    标签: php arrays multidimensional-array associative-array


    【解决方案1】:
    <?php
    $customer_id = array(4, 5);
    $hobies = array('circket', 'chess');
    $output = array();
    foreach($customer_id as $index=>$cid){
        $output[$customer_id[$index]] = array("hobies"=>$hobies[$index]);
    }
    var_dump($output);
    

    输出是

    array(2) {
      [4]=>
      array(1) {
        ["hobies"]=>
        string(7) "circket"
      }
      [5]=>
      array(1) {
        ["hobies"]=>
        string(5) "chess"
      }
    }
    

    【讨论】:

    • 所有关联数组都在您的解决方案中进行了硬编码。这不是这个问题的一般解决方案。考虑例如stackoverflow.com/questions/1536827/…我的天哪,php确实很难,不是吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    相关资源
    最近更新 更多