如何在php中为followg输入创建多维数组

时间:2017-08-18 03:59:30

标签: php arrays codeigniter multidimensional-array

我有输入数组格式,我转换成多维数组

Array
(
    [0] => Array
        (
            [third_party_id] => 2
            [third_party_name] => aardvarkg
            [parameter_id] => 221
            [parameter_name] => new2
            [param_value] => 1
            [sub_param_name] => new2_new2
            [sub_param_value] => 1_1
            [sub_bidder_id] => 72
        )
          [1] => Array
        (
            [third_party_id] => 2
            [third_party_name] => aardvarkg
            [parameter_id] => 222
            [parameter_name] => new
            [param_value] => 1
            [sub_param_name] => new
            [sub_param_value] => 1
            [sub_bidder_id] => 74
        )
    [2] => Array
        (
            [third_party_id] => 3
            [third_party_name] => aard
            [parameter_id] => 221
            [parameter_name] => new2
            [param_value] => 3
            [sub_param_name] => new2
            [sub_param_value] => th
            [sub_bidder_id] => 78
        )
)

我需要的输出是多维数组format.parent和子数组。

 [0] => Array
        (
            [third_party_id] => 2
            [third_party_name] => aardvarkg
            [param]                =>[parameter_id] => 221
                                  [parameter_name] => new2
                                  [param_value] => 1
                                  [subparam]           => [sub_param_name] => new2_new2
                                                   [sub_param_value] => 1_1
                                                    [sub_bidder_id] => 72
        )

我需要输出答案高于数组格式。任何帮助的人都将被关注

3 个答案:

答案 0 :(得分:2)

传递你的二维数组如下

foreach($yourarray as $key=>$array)
{ 
$i = 1;
    foreach($array as $names=>$values)
    {
    if($i<=2)
    {
    $multidimension[$key][$names] = $values; 
    }
    if($i>=3 && $i<=5)
    {
        $multidimension[$key]['param'][$names] = $values; 
    }
    if($i>5)
    {
        $multidimension[$key]['param']['subparam'][$names] = $values; 
    }
    $i++;
    }
}

print_r($multidimension); //expected array output

答案 1 :(得分:0)

我认为应该是这样的

$a = array
(
    array
        (
           "third_party_id" => 2,
            "third_party_name" => 'aardvarkg',
            "parameter_id" => 221,
            "parameter_name" => 'new2',

              "param" =>  array(
        "param_value" => 1),
              "sub_param" => array(
        "sub_param_name" => 'new2_new2',
        "sub_param_value" => '1_1',
        "sub_bidder_id" => 72)
    )

);
  print_r($a);

答案 2 :(得分:0)

您可以使用array_map和array_slice,查看live demo

$result = array_map(function($v){
  $temp = array_slice($v, 0, 2);
  $temp['param'] = array_slice($v, 2, 3);
  $temp['param']['subparam'] = array_slice($v, 5);
  return $temp;
}, $arr);