views:

57

answers:

2

we have these arrays....

$cities = array("nagpur","kanpur","delhi","chd","Noida","mumbai","nagpur");
$names = array("munish","imteyaz","ram","shyam","ankit","Rahul","mohan");

now i want a 2 dimensional array with name of city as key and all the corresponding names as its values.

<?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>";
}

wat i tried is this.but it doesnt work.help me

A: 

You can't expect PHP to guess how to pair those, now can you?

What you actually want to do is:

$final=array(
    "nagpur" => array("munish","imteyaz"),
    "kanpur" => array("ram","shyam"),
    etc.
);

then, if you also need the separate arrays, you build those iterating the $final one, not the other way around.

complete code:

$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);
    }
}
Lo'oris
can u describe it a bit more plz....am not getting it.
ankit
here it is, I've added the second part of the code
Lo'oris
+1  A: 

Try this:

<?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);
?>

Let know how it goes.

pinaki
thnx:) it works fine. can you please help me with one more thing.like i want to sort the names in alphabetiacal order
ankit
like for nagpur it shd me first aman and then ankit
ankit
foreach($arr as }Should sort. Let know if it works. Also consider giving an upvote and accepting the answer if it does what you need.
pinaki