0

I have following 2 arrays

    $Name = Array
         (
          [0] => A
          [1] => B
          [2] => C
          [3] => D
         )

    $zip = Array
    (
        [0] => 411023
        [1] => 411045
        [2] => 411051
        [3] => 411023
    )

Final array should be like this

    $final = Array
         (
          411045 => B
          411051 => C
          411023 => A B
         )

Hope you guys get it what i mean to say.

0

3 Answers 3

1

Here is another solution :

<?php
    $Name             = Array('A','B','C','D');
    $zip              = Array(411023,411045,411051,411023);

    $namezip          = array_combine($Name,$zip);
    $res              = array();
    foreach($namezip as $nam=>$zp){
       if(array_key_exists($zp,$res)){
          $res[$zp]  .= " ".$nam;
       }
       else{
          $res[$zp]   = $nam;
       }
    }

    echo "<pre>";
    print_r($res);
?>
Sign up to request clarification or add additional context in comments.

Comments

1
$name = array ('A', 'B', 'C', 'D');
$zip = array (411023, 411045, 411051, 411023);
$final = array ();

for ($i = 0; $i < sizeof ($zip); $i++)
{
    $n = $name [$i];
    $z = $zip [$i];

    if (!array_key_exists ($z, $final))
        $final [$z] = array ();

    $final [$z][] = $n;
}

print_r ($final);

1 Comment

Mikhail Vladimirov Thanks for the snippet. but again i have to add following code to make resultant array. foreach($final as $Key=>$val) { $names = ""; foreach($val as $k=>$v) { $names .=' '.$v; } $Final_arry[$Key] = $names; }
1

You are looking for the second use case of phps array_keys() function where you can specify a value range. Using that you can simply iterate over the second array:

$final=array();
foreach ($zip as $key=>$anchor) {
  if (! array_key_exists($final,$key))
    $final[$key]=array();
  $final[$key][]=array_keys($name,$anchor);
}

This generates a result $final where each element is an array again, most likely what you want. One could also interpret your question as if you ask for a space separated string, in that case just additionally convert the resulting array:

foreach ($final as $key=>$val)
  $final[$key]=implode(' ',$val);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.