Jump to content

[SOLVED] Multi-Dimensional Array: arrange all values by same keys?


Anti-Moronic

Recommended Posts

OK..I've searched and searched and have no idea if a function exists for this. I'm fairly beginner minded when it comes to advanced array functions.

 

Here's my array:

 

<?php

array(
array('key1'=>'1')
array('key1'=>'2')
array('key2'=>'3')
);

What I want to produce is one array, like so:

array('key1'=>'1,2','key2'=>'3');

?>

 

My head is absolutely spinning with this. Any help is *greatly* appreciated.

I don't think there is a function in PHP that does that for you, but you can make a function like this:

<?php
$test = array(
array('key1'=>'1'),
array('key1'=>'2'),
array('key2'=>'3')
);
print_r(mergeKeys($test));

function mergeKeys($array)
{
   $new = array();
   foreach ($array as $t)
   {
      $cKey = key($t);
      if (!array_key_exists($cKey, $new))
         $new = array_merge($new, array($cKey => current($t)));
      else
         $new[$cKey] .= "," . current($t);
   }
   return $new;
}
?>

Wow, thanks lemmin. Sadly, it doesn't seem to work for me.

 

Input:

Array
(
    [0] => Array
        (
            [18266] => 1
        )

    [1] => Array
        (
            [18266] => 2
        )

    [2] => Array
        (
            [18266] => 3
        )

    [3] => Array
        (
            [18266] => 4
        )

    [4] => Array
        (
            [18266] => 5
        )

    [5] => Array
        (
            [18289] => 6
        )

    [6] => Array
        (
            [18289] => 7
        )

    [7] => Array
        (
            [18289] => 8
        )

    [8] => Array
        (
            [18289] => 9
        )

)

 

Output:



Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)

 

-------------------

 

Do you know where I'm going wrong or if the code needs tweaking?

 

Thanks for you help!

Oh, that's because array_merge won't duplicate numeric keys. I'm not sure why I used that in the first place. Try it like this:

<?php
$test = array(
array('key1'=>'1'),
array('key1'=>'2'),
array('key2'=>'3')
);
print_r(mergeKeys($test));

function mergeKeys($array)
{
   $new = array();
   foreach ($array as $t)
   {
      $cKey = key($t);
      if (!array_key_exists($cKey, $new))
         $new[$cKey] = current($t);
      else
         $new[$cKey] .= "," . current($t);
   }
   return $new;
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.