如何在多维数组PHP中添加新键并合并数组值

时间:2012-08-21 08:42:30

标签: php multidimensional-array array-merge

这是我的第一个功能的结果:

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列表。请帮助我,请耐心等待我的问题,我只是一个初学者。谢谢你得多。

3 个答案:

答案 0 :(得分:0)

这段代码工作正常。 $ a是你的第一个数组$ b是第二个,$ c是结果

$ a = array(array('Maid'=> 1,'Stores'=> array(1,5)),array('Maid'=> 3,'Stores'=> array( 4)),array('Maid'=> 4,'Stores'=> array(1)));

$ b = array(array('Maid'=> 1,'Cash'=> 10000,'借记'=> 0,'信用'=> 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);`

答案 1 :(得分:0)

我在这里测试过它没关系。 (只需将$ a替换为第一个数组,将$ b替换为seccond)。 你确定数组的结构与你上面写的一模一样吗?也许这有任何问题。 你在另一个阵列中插入了数组? (我认为不需要)

Howerver:对于此代码:

`$ a = array(array('Maid'=> 1,'Stores'=> array(1,5)),array('Maid'=> 3,'Stores'=>数组(4)),array('Maid'=> 4,'Stores'=> array(1)));     $ b = array(array('Maid'=> 1,'Cash'=> 10000,'借记'=> 0,'信用'=> 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>";`

输出结果为:

数组([0] =&gt;数组([Maid] =&gt; 1 [商店] =&gt;数组([0] =&gt; 1 [1] =&gt; 5))[1] =&gt;数组([Maid] =&gt; 3 [商店] =&gt;数组([0] =&gt; 4))[2] =&gt;数组([Maid] =&gt; 4 [商店] =&gt;数组([] 0] =&gt; 1)))

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

数组([0] =&gt;数组([女佣] =&gt; 1 [现金] =&gt; 10000 [借记] =&gt; 0 [信用] =&gt; 0))

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

数组([0] =&gt;数组([女佣] =&gt; 1 [现金] =&gt; 10000 [借记] =&gt; 0 [信用] =&gt; 0)[MaidsID] =&gt;数组( [0] =&gt; 1 [1] =&gt; 3 [2] =&gt; 4))

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

这不是你想要的结果吗?

答案 2 :(得分:-1)

看看这个。也许这可以帮到你。

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