atpatil11
atpatil11

Reputation: 433

How to format following array in resultant array in php

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.

Upvotes: 0

Views: 84

Answers (3)

Prasanth Bendra
Prasanth Bendra

Reputation: 32730

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

Upvotes: 1

arkascha
arkascha

Reputation: 42915

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

Upvotes: 1

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

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

Upvotes: 1

Related Questions