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

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

從數組中提取元素,其鍵以PHP中的特定id結尾

從數組中提取元素,其鍵以PHP中的特定id結尾

PHP
30秒到達戰場 2022-07-09 09:36:41
如何提取鍵以 id 結尾的元素?我想通過鍵將一個數組分成兩個數組,其中每個元素都有一個以它的 id 結尾的鍵。數組:array(      'key_1' => 'some value 1',      'key_2' => 'some value 2',     );現在,我有兩個 ID,1 和 2。預期的數組:array_one(      'id' => 1,      'value' => 'some value 1',     );array_two(      'id' => 2,      'value' => 'some value 2',     );實際上,我有一個來自表單的 $_POST 數組。每個鍵都以其 Id 結尾,我想通過它們的 Id 將主數組分成兩個數組。這是我擁有的數組:    Array(    [itemId_1] => 1    [product_id_1] => 1    [desc_1] => desc for the first item    [quantity_1] => 5    [unit_1] => kilogram    [priceUnit_1] => 100    [discount_1] => 0    [taxCost_1] => 45    [itemId_2] => 2    [product_id_2] => 2    [desc_2] => desc for the second item    [quantity_2] => 10    [unit_2] => metre    [priceUnit_2] => 150    [discount_2] => 0    [taxCost_2] => 135)現在,我希望這些數組將它們中的每一個保存到數據庫中。數組必須用 itemId 分隔:    Array(    [itemId] => 1    [product_id] => 1    [desc] => desc for the first item    [quantity] => 5    [unit] => kilogram    [priceUnit] => 100    [discount] => 0    [taxCost] => 45)    Array(    [itemId] => 2    [product_id] => 2    [desc] => desc for the second item    [quantity] => 10    [unit] => metre    [priceUnit] => 150    [discount] => 0    [taxCost] => 135)
查看完整描述

2 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

您可以foreach像這樣編輯數組并將結果存儲在新數組中。


$items = array(

    'key_1' => 'some value 1',

    'key_2' => 'some value 2',

);


$result = array(); 


foreach ($items as $index => $value){

    $id = str_replace('key_','',$index);

    $result['array_'.$id] = [

        'id' => $id,

        'value' => $value,

    ];

}


extract($result); // must return array_1 and array_2


查看完整回答
反對 回復 2022-07-09
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

好的,我已經這樣做了:


foreach ($_POST as $key => $value) {

           $array{$id[1]} = array();

           $id = explode('_', $key);

           ${"array" . $id[1]}[] = array($id[0] => $value);

        }


        $array1 = call_user_func_array('array_merge', $array1);

        var_dump($array1);


        $array2 = call_user_func_array('array_merge', $array2);

        var_dump($array2);

這會給我兩個數組:


    Array

(

    [itemId] => 1

    [product_id] => 1

    [desc] => desc for the first item

    [quantity] => 5

    [unit] => kilogram

    [priceUnit] => 100

    [discount] => 0

    [taxCost] => 45

)


    Array

(

    [itemId] => 2

    [product_id] => 2

    [desc] => desc for the second item

    [quantity] => 10

    [unit] => metre

    [priceUnit] => 150

    [discount] => 0

    [taxCost] => 135

)


查看完整回答
反對 回復 2022-07-09
  • 2 回答
  • 0 關注
  • 120 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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