0

我正在尝试使用另一个数组(基于从数据库返回的行)设置一个空数组的值。

我已经尝试了一些类似的东西,array_merge但我最终只是添加到第一个数组中。

只是好奇是否有办法做到这一点,还是我需要迭代每个数组并将它们合并?

第二个数组可以有 1 到 3 个数组,而第一个(“空”)数组总是有 3 个元素。

Empty array

(
    [0] => Array
        (
            [id] => 
            [quote_id] => 
            ...
        )

    [1] => Array
        (
            [id] => 
            [quote_id] => 
            ...
        )

    [2] => Array
        (
            [id] => 
            [quote_id] => 
            ...
        )

)

我想从中复制数据的数组

Array
(
    [0] => Array
        (
            [id] => 1
            [quote_id] => 1
            ...
        )

    [1] => Array
        (
            [id] => 2
            [quote_id] => 1
            ...
        )

) 

我想要达到的目标

Array
(
    [0] => Array
        (
            [id] => 1
            [quote_id] => 1
            ...
        )

    [1] => Array
        (
            [id] => 2
            [quote_id] => 1
            ...
        )

      [2] => Array
        (
            [id] => 
            [quote_id] => 
            ...
        )

) 
4

4 回答 4

2

您可以使用数组联合运算符Docs

$combined = $rows + $empty;

+运算符返回附加到左侧数组的右侧数组;对于两个数组中都存在的键,将使用左侧数组中的元素,而忽略右侧数组中的匹配元素。

于 2012-10-01T10:34:29.547 回答
0

您可以使用array_replace(),但您必须非常小心键,请参阅PHP 手册中的示例。

于 2012-10-01T10:30:22.817 回答
0

你可以试试

$empty = array(
"0" => Array("id" => null,"quote_id" => null,"position" => null,"type" => null,"number" => null,"cost" => null,"total" => null),
"1" => Array("id" => null,"quote_id" => null,"position" => null,"type" => null,"number" => null,"cost" => null,"total" => null),
"2" => Array("id" => null,"quote_id" => null,"position" => null,"type" => null,"number" => null,"cost" => null,"total" => null))

;

$content = Array(
"0" => Array("id" => 1,"quote_id" => 1,"position" => 1,"type" => "dwdwdw","number" => 22,"cost" => 33.00,"total" => 726.00),
"1" => Array("id" => 2,"quote_id" => 1,"position" => 2,"type" => "dwdw","number" => 22,"cost" => 22.00,"total" => 484.00));



var_dump(array_merge($content,array_unique($empty)));

输出

array
  0 => 
    array
      'id' => int 1
      'quote_id' => int 1
      'position' => int 1
      'type' => string 'dwdwdw' (length=6)
      'number' => int 22
      'cost' => float 33
      'total' => float 726
  1 => 
    array
      'id' => int 2
      'quote_id' => int 1
      'position' => int 2
      'type' => string 'dwdw' (length=4)
      'number' => int 22
      'cost' => float 22
      'total' => float 484
  2 => 
    array
      'id' => null
      'quote_id' => null
      'position' => null
      'type' => null
      'number' => null
      'cost' => null
      'total' => null
于 2012-10-01T10:31:36.347 回答
0

试试这个,

<?php
 $result=mysql_query($query);
 $i=0;
 while($row=mysql_fetch_assoc($result)){
 $youArray[$i]['id']=$row['id'];
 $youArray[$i]['quote_id']=$row['quote_id'];
 //remaining values
 $i++;
 }
?>
于 2012-10-01T10:35:53.047 回答