Search code examples
phpjoomla

How to create a usable array from object


I have a JSON array returned from db query in Joomla, using loadRow().
We're using Custom Fields for some fancy page stuff.

I need the text/value pair from this single record, in a different usable array.

I have tried explode, array_map, lots of different manipulation but I'm struggling with the right combination of code.

This is what the object looks like.

Array ( [0] =>   
    {"options":  
        {"options0":  
            {"name":"soph","value":"School of Public Health"},  
        "options1":  
            {"name":"son","value":"School of Nursing"},  
        "options2":  
            {"name":"sohp","value":"School of Health Professions"}  
        }
    }
)

What I need, something more like this:

Array (
    [0] => {"name":"soph","value":"School of Public Health"},  
    [1] => {"name":"son","value":"School of Nursing"},  
    [2] => {"name":"sohp","value":"School of Health Professions"}
)

Solution

  • Looks like you're storing this in the DB as JSON data. Something like this should work:

    $row = json_decode($arr[0], true)['options'];
    $optionList = [];
    foreach($row as $option => $options)
    {
       array_push($optionList, [
          'name' => $options['name'],
          'value' => $options['value']
       ]);
    }
    

    putting your new data in $optionList.