这里需要一些关于数组的帮助。我需要比较数据库结果中的数组ID。如果存在于数组中。将根据数组的相应ID
覆盖数据库结果如果我们有这个数组的示例:
Array(
[0] => Array(
[company_id] => 1,
[new_lat] => 015244,
[new_long] => 012991
),
[1] => Array(
[company_id] => 2,
[new_lat] => 475421,
[new_long] => 021413
),
[2] => Array(
[company_id] => 3,
[new_lat] => 454544,
[new_long] => 122513
)
)
我有这个代码来分配值。
for ($i = 0; $i <= $companies_count; $i++) :
$company = $companies[$i];
$company_id = $company['company_id']; //this is the ID from the database result
/********These files are from array but I don't know how to search an ID in the array if existing*********/
//file information from textfile
//$file_id = $addresses_file[$i]['company_id'];
//$file_latitude = $addresses_file[$i]['new_lat'];
//$file_longitude = $addresses_file[$i]['new_long'];
//This is the assigning part. If found in the array use the array information instead of the database information
if($company_id == $file_id){
//if found, get information from textfile
$lat = $file_latitude;
$long = $file_longitude;
//echo "found";
}else{
//if not found in then textfile get database info instead
//echo "not found";
$lat = $additionals[$company_id]['geo_lat'];
$long = $additionals[$company_id]['geo_long'];
}
另一个例子假设我们在数据库中有这个:
company_id: 1
new_lat: 454451
new_long: 11211
company_id: 2
new_lat: 232332
new_long: 324343
company_id: 3
new_lat: 34232
new_long: 74874
company_id: 4
new_lat: 34434
new_long: 34344
现在我们的数组中有这个:
company_id: 1
new_lat: 222222
new_long: 11211
company_id: 2
new_lat: 454451
new_long: 11211
所以最终的数组应该是
company_id: 1
new_lat: 222222
new_long: 11211
company_id: 2
new_lat: 454451
new_long: 11211
company_id: 3
new_lat: 34232
new_long: 74874
company_id: 4
new_lat: 34434
new_long: 34344
正如您所见,company_id 1和2被覆盖。 我怎么能那样做呢?
答案 0 :(得分:0)
好的,我有这个代码。我需要做的就是在主循环中执行另一个循环并使用if语句进行比较:
$addresses_file = unserialize(file_get_contents('addresses.txt'));
for ($i = 0; $i <= $companies_count; $i++) :
$company = $companies[$i];
$company_id = $company['company_id'];
//file information from textfile
$file_id = $addresses_file[$i]['company_id'];
$file_latitude = $addresses_file[$i]['new_lat'];
$file_longitude = $addresses_file[$i]['new_long'];
foreach($addresses_file as $y){
if($company_id == $y['company_id']){
$lat = $y['new_lat'];
$long = $y['new_long'];
}else{
$lat = $additionals[$company_id]['geo_lat'];
$long = $additionals[$company_id]['geo_long'];
}
}