PHP将变量推送到array1然后在循环中将其推送到array2

时间:2018-04-26 04:05:17

标签: php arrays array-push

我无法获得数组的目标结果。

我想做的是:

  • 在每个循环中推送$inner_data中的每个变量。
  • 然后将$details_data推送到array以在array
  • 内创建$details_data = array(); $inner_data = array(); for($i=0; $i < $count_selected; $i++){ $amount[$i] = $quantity[$i] * $price[$i]; array_push($inner_data, $last_insert_id, $amount[$i], $quantity[$i], $products[$i]); array_push($details_data, $inner_data); } print_r($details_data); exit;

我希望我能解释一下我的想法和问题。

代码

$data = array(
        array(
                'last_insert_id' => 10,
                'amount' => 20000,
                'quantity' => 1,
                'product_id' => 1
        ),
        array(
                'last_insert_id' => 10,
                'amount' => 1000,
                'quantity' => 1,
                'product_id' => 2
        )
);

目标结果

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

    [1] => Array
        (
            [0] => 10
            [1] => 20000
            [2] => 1
            [3] => 1
            [4] => 10
            [5] => 10000
            [6] => 1
            [7] => 2
        )

)

意外结果

{{1}}

3 个答案:

答案 0 :(得分:1)

for($i=0; $i < $count_selected; $i++){
    $amount[$i] = $quantity[$i] * $price[$i];

    $inner_data=array(
      'last_insert_id'=>$last_insert_id, 
      'amount'=>$amount[$i], 
      'quantity'=>$quantity[$i], 
      'product_id'=>$products[$i]
    );
    array_push($details_data, $inner_data);
}

答案 1 :(得分:1)

Link for your reference

<?php

    $details_data = array();

    /* do not set it as a global vari OR clear it when you re-use it */
    //$inner_data = array();

    $last_insert_id = 10;
    $amount = [20000, 1000];
    $quantity = [110, 220];
    $price = [32, 64];
    $products = [001, 002];

    for($i=0; $i < 2; $i++){
        $amount[$i] = $quantity[$i] * $price[$i];

        /* set it here as a local vari, thus it won't accumulate the result */
        $inner_data = array();

        //array_push($inner_data, $last_insert_id, $amount[$i], $quantity[$i], $products[$i]);
        $inner_data['last_insert_id'] = $last_insert_id;
        $inner_data['amount'] = $amount[$i];
        $inner_data['quantity'] = $quantity[$i];
        $inner_data['product_id'] = $products[$i];
        array_push($details_data, $inner_data);
    }

    echo "<pre>";
    print_r($details_data); exit;

    echo "</pre>";

?>

答案 2 :(得分:0)

array_push($details_data, 
array('last_insert_id'=>$last_insert_id, 'amount'=>$amount[$i], 'quantity'=>$quantity[$i], 'product_id'=>$products[$i])
);

尝试将数组直接推送到details_data。