0

I have some data that is coming from a mysql query in a flat array this way:

  0 => Array 
    indcode => "A00"
    indlabel => "Code label text"
    description => "More explanations"
  1 => Array 
    indcode => "NA0"
    indlabel => "Un-classified A"
    description => "Un-classified A"
  2 => Array (3)
    indcode => "A01"
    indlabel => "Code Label text"
    description => "More explanations"
  3 => Array (3)
    indcode => "A02"
    indlabel => "Code label text"
    description => "More explanations"

I would like to nest it that way:

  A00 => Array 
    indlabel => "Code label text"
    description => "More explanations"
  NA0 => Array 
    indlabel => "Un-classified A"
    description => "Un-classified A"
  A01 => Array 
    indlabel => "Code Label text"
    description => "More explanations"
  A02 => Array
    indlabel => "Code label text"
    description => "More explanations"

So in my CMS I found in use a very neat code which does the nesting :

foreach ($dimsDesc as $desc) {
$descriptions[$desc['indcode']][$desc['indlabel']] = $desc['description'];
}

That works but I didn't find how to keep the indlabel and description at the same level (= the other side of the equal sign).

Also, if you have links to some other examples or a good reference for this construct, it would be appreciated because I will use this a lot to build dynamic reports... And for now PDO queries are a bit out of my reach. I also used array_column() with NULL which works but I have more complex data structures incoming...

2 Answers 2

1

You're almost there, just change your foreach loop in the following way,

foreach ($dimsDesc as $desc) {
    $descriptions[$desc['indcode']]['indlabel'] = $desc['indlabel'];
    $descriptions[$desc['indcode']]['description'] = $desc['description'];
}

Or,

foreach ($dimsDesc as $desc) {
    $descriptions[$desc['indcode']] = array('indlabel' => $desc['indlabel'], 'description' => $desc['description']);
}

Here's the documentation,

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, all do work, but especially the first example that even if it looks somehow less neat than the second, it helped me to understand what I had missed !
Thanks indeed. I was wondering if there is some (book, online documentation, ...) where I can find some examples or explanations. I was especially wondering why this works (instead of overwriting the values or duplicating the arrays...)..
1

Try this,

<?php
foreach ($dimsDesc as $desc) {
    $descriptions[$desc['indcode']] = array( 
        'indlabel' => $desc['indlabel'], 
        'description' => $desc['description']
    );
}
?>

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.