我有以下两个数组:
$cars = array("BMW", "VW", "Kia", "Ford", "Ferrari", "Lamborghini");
$for_sale = array(
array(
"engine_capacity" => "1600",
"car_id" => 5,
"year" => 1937),
array(
"engine_capacity" => "2400",
"car_id" => 0,
"year" => 1937),
array(
"engine_capacity" => "2000",
"car_id" => 3,
"year" => 1937),
array(
"engine_capacity" => "2000",
"car_id" => 4,
"year" => 1937),
array(
"engine_capacity" => "4800",
"car_id" => 2,
"year" => 1937),
array(
"engine_capacity" => "6000",
"car_id" => 1,
"year" => 1937),
);
我正在尝试将$ cars中的索引与$ for_sale中的'car_id'值匹配,然后显示匹配的汽车名称。即“car_id”=> 0将显示BMW等。我看过各种类似的问题,但是他们帮助很小。任何帮助都会非常感激,因为我在这项任务中一直都很失败。 Thankx。
答案 0 :(得分:1)
如果要合并两个数组,为了在car_id
数组中包含car_name
和$for_sale
,请尝试使用:
for($i = 0; $i < count($cars) && $i < count($for_sale); $i++) {
$for_sale[$i]['car_name'] = $cars[$i];
}
var_dump($for_sale);
<强> PHP Fiddle 强>
答案 1 :(得分:1)
检查
for($i = 0; $i < count($cars) && $i < count($for_sale); $i++) {
$for_sale[$i]['car_id'] = $cars[$i];
}
var_dump($for_sale);
将$for_sale[$i]['car_name']
更改为$for_sale[$i]['car_id']
您将获得正确的结果
现在[0]将是宝马的索引等等。
答案 2 :(得分:0)
你的意思是你想根据car_id输出汽车的价值,其中car_id是汽车的索引,如:
echo $cars[$for_sale[1]['car_id']]
这应该回应BMW
修改强>
显示所有待售的车名,这将是一种方法:
foreach($for_sale as $fs) {
if (isset($cars[$fs['car_id']])) {
echo $cars[$fs['car_id']];
}
}
答案 3 :(得分:-1)
**使用此代码工作.. **
foreach($for_sale as $k =>$v){
foreach($cars as $key => $val){
if($for_sale[$k]['car_id'] == $key){
echo $cars[$key];
}
}
}
解决此问题的另一种方法是:
foreach($for_sale as $k =>$v){
$for_sale[$k]['car_name'] = $cars[$v['car_id']];
}