基本数组构建

猜猜这是一个基本问题。 如何使用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';
        }

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

评论
  • _樱花巷
    _樱花巷 回复

    使用给定的代码,您可以在该循环的每一行中在数组中创建新的内部行。以下代码将解决该问题:

    $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;
    }
    
  • Lee
    Lee 回复

    您相当接近执行此操作的一种方法...

    说明:

    $arr[]['ProductGuid'] = $item->guid;
        ^^
        \= Next numeric array key.
    

    What this is doing is setting the productGuid key on the next numeric outer array, so in effect what you're actually setting is:

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

    显然这不是您想要的。

    解:

    Therefore you will have to set the array key value on each iteration of the foreach loop.

    一种方法是手动设置迭代器整数键值:

    $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
    }