这里需要一点帮助。因为我正在创建一个数组列表。我需要使用条件替换数组的值。在验证条件时,我没有错误。但当我更换我的阵列时,它不会取代。对不起,我的英语不好。我希望你明白我的意思。这是我的代码。
这是我的BASE数组:
Array
(
[0] => Array
(
[restaurant_id] => 1519
[new_lat] => 14.63809
[new_long] => 121.03242
[date_updated] => 2013-11-14 18:53:20
)
)
现在我将把这个数组替换成这个数组
Array
(
[0] => Array
(
[restaurant_id] => 1519
[new_lat] => 14.63796
[new_long] => 121.03278
[date_updated] => 2013-11-15 06:54:32
)
)
现在我使用了array_replace();
这是输出:
Array
(
[0] => Array
(
[restaurant_id] => 1519
[new_lat] => 14.63809
[new_long] => 121.03242
[date_updated] => 2013-11-14 18:53:20
)
[restaurant_id] => 1519
[new_lat] => 14.63796
[new_long] => 121.03278
[date_updated] => 2013-11-15 06:54:32
)
在我生成数组的代码中:
//THIS IS MY UPDATED ARRAY
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
$data = unserialize(file_get_contents('addresses.txt')); //THIS IS THE BASE ARRAY
//GET THE ID OF UPDATED ARRAY AND FIND IN THE BASE ARRAY - IF EXIST, UPDATE ONLY. IF NOT SIMPLY ADD
$target = $data_add['restaurant_id'];
for ($i = 0; $i < count($data); $i++) {
$get_id = $data[$i]['restaurant_id'];
if($get_id == $target){
//if found update/delete specific row
echo "found";
$add_data = array();
$add_data = array(
$i => $data_add
);
$new_array = array();
$new_array = array_replace($data,$data_add);
}else{
//if not found add
echo "not found";
$data[] = $data_add;
}
}
显示:
echo "<pre>";
echo "BASE ARRAY<br />";
print_r($data);
echo "---------------------------------------------------------<br />";
echo "NEW ARRAY<br />";
print_r($add_data);
echo "---------------------------------------------------------<br />";
echo "REPLACED ARRAY<br />";
print_r($new_array);
echo "---------------------------------------------------------<br />";
知道我的代码出错了吗?请帮帮我们。提前致谢。 :)
答案 0 :(得分:0)
更改此行 -
$new_array = array_replace($data,$data_add);
到此 -
$new_array = array_replace($data[0], $data_add);
$ data_add的结构不像是在输出中将其描绘在上面。您可以使用此代码创建$ data_add -
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
如果您实际输出该数组,它将如下所示 -
Array
(
[restaurant_id] => 1519
[new_lat] => 14.63796
[new_long] => 121.03278
[date_updated] => 2013-11-15 06:54:32
)
因此,您需要将$ data_add替换为$ data [0],因为您要替换$ data的第0个索引。