[英]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[]" 我有一个当前看起来像这样的数组:其来自名称为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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.