简体   繁体   中英

Create an associative multidimensional array from an index array in php

I have an array which currently looks like this: its from a form with names like 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 
         )

Now i want it to look like the array below so i can pass it into database:

   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'
)
);

I believe this is very much possible but i can not figure a way around it yet

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

As an alternative:

$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);

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