我正在尝试使用另一个数组(基于从数据库返回的行)设置空数组的值。
我尝试了一些像array_merge
这样的东西,但我最后才添加到第一个数组中。
只是好奇是否有办法做到这一点,还是我需要迭代思考每个数组并合并它们?
第二个数组中可以包含1到3个数组,而第一个数组(“empty”)数组总共有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] =>
...
)
)
答案 0 :(得分:2)
您可以使用array union operatorDocs:
$combined = $rows + $empty;
+ 运算符返回附加到左侧数组的右侧数组;对于存在于两个数组中的键,将使用左侧数组中的元素,并且将忽略右侧数组中的匹配元素。
答案 1 :(得分:0)
您可以使用array_replace()
,但是您必须非常小心这些键,请参阅PHP manual中的示例。
答案 2 :(得分: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
答案 3 :(得分: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++;
}
?>