簡體   English   中英

php按鍵在多維數組中組合數組

[英]php Combining arrays within a multidimensional array by key

我有$ _POST的以下數組:

array { 
["item"]=> array() { 
    [0]=> "pen" 
    [1]=> "pencil" 
    [2]=> "ruler" 

array { 
["note"]=> array() { 
    [0]=> "permanent" 
    [1]=> "not so permanent" 
    [2]=> "measures stuff" 

array { 
["cost"]=> array() { 
    [0]=> "67.99" 
    [1]=> ".15" 
    [2]=> "1.49"

我希望將它組合成單行項目,例如

array { 
["line_items"]=> array() {

["0"]=> array() {
        [item]=> "pen" 
        [note]=> "permanent"
        [cost]=> "67.99"

["1"]=> array() {
        [item]=> "pencil" 
        [note]=> "not so permanent"
        [cost]=> ".15"      

["3"]=> array() {
        [item]=> "ruler" 
        [note]=> "measures stuff"
        [cost]=> "1.49" 

我已經看過array_merge,array_merge_recursive,array_combine,但所有這些函數都沒有做我正在尋找的東西。 我已經為每個和循環嘗試了一些不同的東西,但我無法理解它。

請問你是否需要更多的信息,這不是很清楚,但就像我說的,我的頭 - 努力解決這個問題。

你必須自己想出一些東西:

$length = count($_POST['item']);
$items = array();
for ($i = 0; $i < $length; $i++) {
    $item = array();
    $item['item'] = $_POST['item'][$i];
    $item['note'] = $_POST['note'][$i];
    $item['cost'] = $_POST['cost'][$i];
    $items[] = $item;
}

var_dump($items);

應該得到你需要的東西。 請注意,它沒有任何錯誤檢查或驗證 - 您需要添加它。

編輯 :在我的回答中犯了一個愚蠢的錯誤 - 糾正了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM