Converting a Multi-dimensional Array Structure

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kennyw
Forum Newbie
Posts: 4
Joined: Mon Aug 10, 2009 1:11 am

Converting a Multi-dimensional Array Structure

Post by kennyw »

Hi,

I have a database query returning the following array structure;

Code: Select all

Array
(
    [0] => Array
        (
            [Category] => Array
                (
                    [id] => 9
                    [name] => ABC
                )
 
            [Ds] => Array
                (
                    [ds_id] => 39
                )
 
        )
 
    [1] => Array
        (
            [Category] => Array
                (
                    [id] => 10
                    [name] => DEF
                )
 
           [Ds] => Array
                (
                    [ds_id] => 40
                )
 
        )
 
)
I need to change the structure of the array(to feed a json object) to this;

Code: Select all

Array
(
    [0] => Array
        (
           [id] => 9
           [name] => ABC
           [ds_id] => 39
         )
 
    [1] => Array
        (
           [id] => 10
           [name] => DEF
           [ds_id] => 40
         )
 
)
I am embarassed to say i have spent the best part of two days mucking around with a multitude of recursive functions to no avail. At best i completely flatten the array at worst i end up with a complete mishmash.

I tried to set up a php debugger to watch the process but after 3 days of trying i came to the conclusion it was not compatible with my working environment. I am still using php 4.4.9. Any assistance would be greatly appreciated
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Converting a Multi-dimensional Array Structure

Post by prometheuzz »

Here's how:

Code: Select all

$array3D = array(
  array('Category' =>
    array('id' => 9, 'name' => 'ABC'),
    array('ds_id' => 39)
  ),
  array('Category' =>
    array('id' => 10, 'name' => 'DEF'),
    array('ds_id' => 40)
  )
);
$array2D = array(array());
$i = 0;
foreach($array3D as $temp2D) {
  foreach($temp2D as $temp1D) {
    foreach($temp1D as $value) {
      $array2D[$i][] = $value;
    }
  }
  $i++;
}
print_r($array2D);
kennyw
Forum Newbie
Posts: 4
Joined: Mon Aug 10, 2009 1:11 am

Re: Converting a Multi-dimensional Array Structure

Post by kennyw »

thanks prometheuzz, but i failed to mention the arrays are dynamic and the depth of nesting unknown, as are the keys/index names. I was attempting to conjour up a more generic method.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Converting a Multi-dimensional Array Structure

Post by prometheuzz »

kennyw wrote:thanks prometheuzz, but i failed to mention the arrays are dynamic and the depth of nesting unknown, as are the keys/index names. I was attempting to conjour up a more generic method.
You're welcome.
Then you need to be a bit more precise. Perhaps even give some more concrete examples. Now you just posted you wanted to convert a 3D array (input) to a 2D array (output). What if the input is a 1D array? What if it's a 4D array? What if it's a n-D array?
frao_0
Forum Commoner
Posts: 27
Joined: Sat Aug 08, 2009 3:52 am
Location: Toulouse, France

Re: Converting a Multi-dimensional Array Structure

Post by frao_0 »

I think the answer is in your SQL request. Is that a joint table query? Give us a view of your table structure, the SQL SELECT query and the method used to retrieved the query (fetch_assoc, fetch_array, etc.). For me, the answer is in the way your query is processed!

Otherwise, when working with arrays parsing with unknown depth, a recursive function is the way to go. Out of my head, it's something like this:

Code: Select all

$myArray=array(...);
 
function parseArray($array,&$items)
{
foreach($array as $k=>$v)
{
if(is_array($v))
parseArray($v);
else
$items[]=$v;
}
return $items;
} 
 
$items=parseArray($myArray);
kennyw
Forum Newbie
Posts: 4
Joined: Mon Aug 10, 2009 1:11 am

Re: Converting a Multi-dimensional Array Structure

Post by kennyw »

frao_0 i'm using the cakephp framework which wraps sql calls in model methods (object relational mapping) - i can generate custom sql queries, but i am trying to aviod it for the time being. The sql is the result of a join relationship between two tables(categories /ds).

i have tried;

Code: Select all

function test ($data = null, $key = null){
$key;
foreach ($data as $k => $v){
if(is_array($v){
if(is_numeric($k){ $key = $k;}
$this->test($v, $key);
}else{
echo "$key:::$k:::$v\n";
}
}
 
The echo out will iterate through the array with:
0::id::9
0::name::ABC
0::ds_id::41
etc

I just have to build a multi dim result set - and my mind has gone blank - i have sprinled the code with array_merge, array_push.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Converting a Multi-dimensional Array Structure

Post by pickle »

It's not completely clear to me what the possible format of the input array is, and what the corresponding output array should be. Are you wanting to only flatten scalar values and their corresponding keys?
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Converting a Multi-dimensional Array Structure

Post by prometheuzz »

pickle wrote:It's not completely clear to me what the possible format of the input array is, and what the corresponding output array should be. Are you wanting to only flatten scalar values and their corresponding keys?
Ditto here. But it seems the OP choose to ignore my request for clarification.
kennyw
Forum Newbie
Posts: 4
Joined: Mon Aug 10, 2009 1:11 am

Re: Converting a Multi-dimensional Array Structure

Post by kennyw »

In the top post the first array is the result set from the database - this then has to altered to fit a json construct - thus the second array is what i needed - here is an answer that does work;

Code: Select all

/**
* Convert a n-dim array to a 1-dim array
* @param array $arr
* @return array
*/
function flatten($arr)
{
   $return = array();
   foreach($arr as $key => $val)
   {
      if(is_array($val))
      {
         $ret = flatten($val);
         $return = $return + $ret;
      }
      else
      {
         $return[$key] = $val;
      }
   }
   return $return;
}
 
// USAGE:
foreach($array as $key => $val)
{
   $array[$key] = flatten($val);
}
I apologise for not being clearer - i thought i was keeping it simple;
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Converting a Multi-dimensional Array Structure

Post by prometheuzz »

kennyw wrote:In the top post the first array is the result set from the database - this then has to altered to fit a json construct - thus the second array is what i needed - here is an answer that does work;
...
I apologise for not being clearer - i thought i was keeping it simple;
No problem. Glad to hear you found a solution!
Post Reply