从php中的索引数组创建一个关联的多维数组

时间:2014-08-22 21:50:26

标签: php arrays multidimensional-array

我有一个目前看起来像这样的数组: 它来自名称如name =“buyer_id []”

的表单
Array ( 
   [product_id] => 
      Array ( 
       [0] => 1 
       [1] => 2 
       [2] => 4 
           ) 
   [name] => 
     Array ( 
      [0] => Paper Choco 
      [1] => Paper Fan Vanilla 
      [2] => Pink Prom 
           ) 
  [staff_id] => 
    Array ( 
      [0] => 1 
      [1] => 1 
      [2] => 1 
          ) 
  [category] => 
    Array ( 
      [0] => agent 
      [1] => agent 
      [2] => agent 
         ) 
  [date] => 
    Array ( 
      [0] => 2014-08-22 
      [1] => 2014-08-22 
      [2] => 2014-08-22 
         ) 
  [price] => 
    Array ( 
      [0] => 188 
      [1] => 887 
      [2] => 17 
         )

现在我希望它看起来像下面的数组,所以我可以将它传递到数据库中:

   array(
     array(
      'product_id' => 1 ,
      'name' => 'Paper Choco',
      'category'=>'agent',
      'staff_id'=> 1,
      'date'=> '2014-08-22'
),
   array(
      'product_id' => 2 ,
      'name' => 'Paper Fan Vanilla ',
      'category'=>'agent',
      'staff_id'=> 1,
      'date'=> '2014-08-22'
),
   array(
      'product_id' => 4 ,
      'name' => 'Pink Prom ',
      'category'=>'agent',
      'staff_id'=> 1,
      'date'=> '2014-08-22'
)
);

我相信这是非常可能的,但我无法想办法呢

2 个答案:

答案 0 :(得分:0)

$result = array();
foreach ($array as $key => $subarray) {
    foreach ($subarray as $i => $value) {
        if (!isset($result[$i])) {
            $result[$i] = array();
        }
        $result[$i][$key] = $value;
    }
}

答案 1 :(得分:0)

作为替代方案:

$data = array ( 
    'product_id' => array ( 1, 2, 4 ),
    'name' => array ( 'Paper Choco', 'Paper Fan Vanilla', 'Pink Prom' ),
    'staff_id' => array ( 1, 1, 1 ),
    'category' => array ( 'agent', 'agent', 'agent', ),
    'date' => array ('2014-08-22', '2014-08-22', '2014-08-22' ),
    'price' => array ( 188, 887, 17 ),
);

function transpose($array) {
    array_unshift($array, null);
    return call_user_func_array('array_map', $array);
}

$result = transpose($data);
array_walk(
    $result,
    function (&$value) use ($data) {
        $value = array_combine(array_keys($data), $value);
    }
);

var_dump($result);