簡體   English   中英

如何在多維數組PHP中添加新鍵並合並數組值

[英]How to Add a new Key and Merge the array values in multidimemsional array PHP

這是我的第一個功能的結果:

Array
(
[0] => Array
    (
        [MaidID] => 13
        [Stores] => Array
            (
                [0] => 14
                [1] => 5
            )
    )

  [1] => Array
     (
        [MaidID] => 3
        [Stores] => Array
            (
                [0] => 4
            )

    )

[2] => Array
    (
        [MaidID] => 41
        [Stores] => Array
            (
                [0] => 14
            )

    )
 )

然后,這是我第二個函數的結果:

  Array
 (
 [1] => Array
    (
        [MaidID] => 14
        [Cash] => 10000
        [Debit] => 0
        [Credit] => 0
    )
  )

結果應該是這樣的:

   Array ([0] => Array (

        [MaidID] => 14
        [Cash] => 10000.00
        [Debit] => 0
        [Credit] => 0   
        [MaidsID] => Array(
                       [0] => 13                          
                       [1] => 41
     )
   )
 )

我需要一個新的密鑰名稱MaidsID來指向多個商店擁有的MaidID列表。請幫助我,請耐心等待我的問題,我只是一個初學者。非常感謝。

此代碼可以正常工作。 $ a是您的第一個數組$ b是第二個數組,$ c是結果

$ a =數組(array('Maid'=> 1,'Stores'=> array(1,5)),array('Maid'=> 3,'Stores'=> array(4)),array('女仆'=> 4,'商店'=>數組(1)));

$ b =數組(array('Maid'=> 1,'Cash'=> 10000,'Debit'=> 0,'Credit'=> 0));

$MaidsID=array();

foreach ($a as $aa ){
    if (count($aa['Stores']>1)){
        array_push($MaidsID, $aa['Maid']);
    }
}
$MaidsID=array('MaidsID' => $MaidsID);

$c = array_merge($b, $MaidsID);`

我在這里測試過,還可以。 (只需將$ a替換為第一個數組,將$ b替換為seccond)。 您確定數組的結構與您上面寫的完全一樣嗎? 也許這有什么問題。 您已將數組放入另一個數組中? (我認為不需要)

但是,對於此代碼:

$ a = array(array('Maid'=> 1,'Stores'=> array(1,5)),array('Maid'=> 3,'Stores'=> array(4)),array( '女仆'=> 4,'商店'=>數組(1))); $ b =數組(array('Maid'=> 1,'Cash'=> 10000,'Debit'=> 0,'Credit'=> 0));

print_r($a);
echo "<br><br>================================================<br><br>";
print_r($b);
echo "<br><br>================================================<br><br>";

$MaidsID=array();

foreach ($a as $aa ){
    if (count($aa['Stores']>1)){
        array_push($MaidsID, $aa['Maid']);
    }
}
$MaidsID=array('MaidsID' => $MaidsID);

$c = array_merge($b, $MaidsID);

print_r($c);
echo "<br><br>================================================<br><br>";`

輸出為:

Array([0] => Array([Maid] => 1 [Stores] => Array([0] => 1 [1] => 5))[1] => Array([Maid] => 3 [商店] =>數組([0] => 4))[2] =>數組([女仆] => 4 [商店] =>數組([0] => 1)))

===============================================

Array([0] => Array([Maid] => 1 [Cash] => 10000 [Debit] => 0 [Credit] => 0)))

===============================================

Array([0] => Array([Maid] => 1 [Cash] => 10000 [Debit] => 0 [Credit] => 0)[MaidsID] => Array([0] => 1 [1] => 3 [2] => 4))

===============================================

這不是您想要的結果嗎?

看看這個。 也許這可以幫助您。

$result = array_merge($array1, $array2);

暫無
暫無

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

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