bquarta bquarta - 3 months ago 11
JSON Question

JSON, nested arrays and the issue of the right order

currently I'm working on a Joomla!-Component, which uses the "repeatable" field-type.
Repeatable stores the data of the different fields into a JSON inside of a database-field.

Okay so far...

The JSON which is stored looks like this:

{"track_number":["1","2"],"track_duration":["00:02:02","00:20:24"],"title":["A Song","Ein Lied"],"file":["",""]}


so json_decode will result in:

stdClass Object
(
[track_number] => Array
(
[0] => 1
[1] => 2
)

[track_duration] => Array
(
[0] => 00:02:02
[1] => 00:20:24
)

[title] => Array
(
[0] => A Song
[1] => Ein Lied
)

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

)


Unfortunately this is not really the optimal JSON-structure for me if i want to output the results in a html-table, since the index of the outer array will run through every "track_number" of every item (in a nested foreach) and so on...

I'd somehow need to make the inner array the outer one and vice versa.
Or find an elegant way how to deal with the nested arrays properly.

I mean if it would look like this it wouldn't be a problem:

stdClass Object
(
[0] => Array
(
[track_number] => 1
[track_duration] => 00:02:02
[title] => A Song
[file] =>
)

[1] => Array
(
[track_number] => 1
[track_duration] => 00:20:24
[title] => Ein Lied
[file] =>
)

)


... but unfortunately this is not how Joomla builds the repeatable field type ;)

I'm getting a bit dizzy with the arrays here, so maybe someone can give me a good advice :)

thanks in advance and best regards

Answer

Its actually quite easy to process the array as it is

stdClass Object
(
    [track_number] => Array
        (
            [0] => 1
            [1] => 2
        )

    [track_duration] => Array
        (
            [0] => 00:02:02
            [1] => 00:20:24
        )

    [title] => Array
        (
            [0] => A Song
            [1] => Ein Lied
        )

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

)

Using a simple echo to demonstrate the method

foreach ($obj->track_number as $idx => $track) {
    echo sprintf( 'Track No %d, Duration %s, Title %s, File %s',  
                  $track,
                  $obj->track_duration[$idx],
                  $obj->title[$idx],
                  $obj->file[$idx]
                );
}