在php中从多个多维数组创建一个数组

时间:2017-05-29 08:47:21

标签: php arrays multidimensional-array

我创建了以下数组。但这不是我想要的。帮助创建一个新的数组,以满足我的要求。

Array (
[supplier_id] => 1
[filter_name] => Array
    (
        [0] => product 1 
        [1] => Product 2
        [2] => Product 3
    )

[quantity] => Array
    (
        [0] => 3
        [1] => 10
        [2] => 2
    )

[unit] => Array
    (
        [0] => pkts
        [1] => ltrs
        [2] => pkts
    )

[price] => Array
    (
        [0] => 11
        [1] => 100
        [2] => 10
    )

[gross_amount] => Array
    (
        [0] => 33
        [1] => 1000
        [2] => 20
    )

[vat] => Array
    (
        [0] => 0
        [1] => 0
        [2] => 0
    )

[net_amount] => Array
    (
        [0] => 33
        [1] => 1000
        [2] => 20
    ) )

这是我想要的数组。有没有想法创建这种类型的数组。

Array(
[supplier_id] = 1
[0] = Array(
    [filter_name] => product 1
    [quantity] => 3
    [unit] => pkts
    [price] => 11
    [gross_amount] => 33
    [vat] => 0
    [net_amount] => 33
)
[1] = Array(
    [filter_name] => product 2
    [quantity] => 10
    [unit] => ltrs
    [price] => 100
    [gross_amount] => 1000
    [vat] => 0
    [net_amount] => 1000
)

[2] = Array(
    [filter_name] => product 3
    [quantity] => 2
    [unit] => pkts
    [price] => 10
    [gross_amount] => 20
    [vat] => 0
    [net_amount] => 20
))

1 个答案:

答案 0 :(得分:1)

我认为这应该对你有所帮助,我假设你的子数组中有最多3个值,所以我使用了while($i<3);

$i = 0;
   $newArray = array();
   do{
   foreach($arr as $key=>$val){
       if($key == 'supplier_id'){
            $newArray[$key] = $val;
        }else{
            $newArray[$i][$key] = $val[$i];
        }

   }
   $i++;   
   }while($i<3);
   echo "<pre>"; print_r($newArray);

Check Output here