基本阵列构建

猜猜这是一个基本问题。如何使用 foreach 循环创建一个与此类似的数组?


          [

            [

                'ProductGuid' => '27760c24',

                'BaseAmountValue' => 240,

                'Quantity' => 1,

                'Discount' => 0,

                'AccountNumber' => 1000,

                'Unit' => 'parts',

            ],

            [

                'ProductGuid' => '27760c24',

                'BaseAmountValue' => 250,

                'Quantity' => 1,

                'Discount' => 0,

                'AccountNumber' => 1000,

                'Unit' => 'parts',

            ]

        ],

以下内容被 API 拒绝,我正在尝试连接到:


        $arr = array();

        foreach($items as $item) {

            $arr[]['ProductGuid'] = $item->guid;

            $arr[]['BaseAmountValue'] = $item->price;

            $arr[]['Quantity'] = $item->qty;

            $arr[]['Discount'] = $item->discount;

            $arr[]['AccountNumber'] = 1000;

            $arr[]['Unit'] = 'parts';

        }

希望你们中的一个能帮助我 :)


万千封印
浏览 156回答 3
3回答

冉冉说

其他两个正确答案的替代方法,但无需手动设置数组索引或使用任何临时变量:$arr = [];foreach($items as $item) {    $arr[] = [        'ProductGuid'     => $item->guid,        'BaseAmountValue' => $item->price,        'Quantity'        => $item->qty,        'Discount'        => $item->discount,        'AccountNumber'   => 1000,        'Unit'            => 'parts',    ];}

12345678_0001

使用给定的代码,您可以在该循环的每一行中在数组中创建新的内部行。下面的代码将解决这个问题:$arr = array();foreach($items as $item) {     $mappedItem = [];     $mappedItem['ProductGuid'] = $item->guid;     $mappedItem['BaseAmountValue'] = $item->price;     $mappedItem['Quantity'] = $item->qty;     $mappedItem['Discount'] = $item->discount;     $mappedItem['AccountNumber'] = 1000;     $mappedItem['Unit'] = 'parts';     $arr[] = $mappedItem;}

哔哔one

你相当接近这样做的一种方式......解释:$arr[]['ProductGuid'] = $item->guid;    ^^    \= Next numeric array key.这样做是在下一个productGuid数字外部数组上设置键,因此实际上您实际设置的是:$arr[0]['ProductGuid'] = $item->guid;$arr[1]['BaseAmountValue'] = $item->price;$arr[2]['Quantity'] = $item->qty;$arr[3]['Discount'] = $item->discount;$arr[4]['AccountNumber'] = 1000;$arr[5]['Unit'] = 'parts';这显然不是你想要的。一种解决方案:因此,您必须在循环的每次迭代中设置数组键值foreach。一种方法是手动设置迭代器整数键值:$arr = [];$x = 0;     foreach($items as $item) {             $arr[$x]['ProductGuid'] = $item->guid;    $arr[$x]['BaseAmountValue'] = $item->price;    $arr[$x]['Quantity'] = $item->qty;    $arr[$x]['Discount'] = $item->discount;    $arr[$x]['AccountNumber'] = 1000;    $arr[$x]['Unit'] = 'parts';    $x++; // +1 to value of $x}
打开App,查看更多内容
随时随地看视频慕课网APP