我们有这些数组......
$cities = array("nagpur","kanpur","delhi","chd","Noida","mumbai","nagpur");
$names = array("munish","imteyaz","ram","shyam","ankit","Rahul","mohan");
现在我想要一个二维数组,其中city的名称为key,所有相应的名称为其值。
<?php
$cities = array("nagpur","kanpur","nagpur","delhi","kanpur");
$names = array("ankit","atul","aman","amit","manu");
foreach ($cities as $i => $value) {
echo "\n";
echo $value;
$city=$value;
$k=0;
foreach ($cities as $ii => $m) {
If($city==$m)
{
echo$names[$ii] ;
$final[$i][$k]=$names[$ii];
$arr = array($city => array($k =>$names[$ii] ));
$k++;
}
}
echo"\n<tr></tr>";
}
我试过的是这个。但它不起作用。帮助我
答案 0 :(得分:2)
试试这个:
<?php
$cities = array("nagpur","kanpur","nagpur","delhi","kanpur");
$names = array("ankit","atul","aman","amit","manu");
$arr = array();
foreach($cities as $key=>$city) {
$arr[$city][] = $names[$key];
}
echo "<pre>";
print_r($arr);
?>
让我们知道它是怎么回事。
答案 1 :(得分:0)
您不能指望PHP猜测如何配对,现在可以吗?
你真正想做的是:
$final=array(
"nagpur" => array("munish","imteyaz"),
"kanpur" => array("ram","shyam"),
etc.
);
然后,如果你还需要单独的数组,你可以构建那些迭代$final
的数组,而不是相反。
完整代码:
$final=array(
"nagpur" => array("munish","imteyaz"),
"kanpur" => array("ram","shyam"),
);
$cities=array();
$names=array();
foreach ($final as $city => $nnn) {
array_push($cities,$city);
foreach ($nnn as $nn) {
array_push($names,$nn);
}
}