亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

基本陣列構建

基本陣列構建

PHP
萬千封印 2023-03-11 13:10:49
猜猜這是一個基本問題。如何使用 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';        }希望你們中的一個能幫助我 :)
查看完整描述

3 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

其他兩個正確答案的替代方法,但無需手動設置數組索引或使用任何臨時變量:


$arr = [];

foreach($items as $item) {

? ? $arr[] = [

? ? ? ? 'ProductGuid'? ? ?=> $item->guid,

? ? ? ? 'BaseAmountValue' => $item->price,

? ? ? ? 'Quantity'? ? ? ? => $item->qty,

? ? ? ? 'Discount'? ? ? ? => $item->discount,

? ? ? ? 'AccountNumber'? ?=> 1000,

? ? ? ? 'Unit'? ? ? ? ? ? => 'parts',

? ? ];

}


查看完整回答
反對 回復 2023-03-11
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

使用給定的代碼,您可以在該循環的每一行中在數組中創建新的內部行。下面的代碼將解決這個問題:


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

}


查看完整回答
反對 回復 2023-03-11
?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

你相當接近這樣做的一種方式......


解釋:

$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

}


查看完整回答
反對 回復 2023-03-11
  • 3 回答
  • 0 關注
  • 137 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號