This for an open source plugin I'm adding a feature to allow using a template to be able to generate output using Handlebars, instead of using PHP for handlebars i want to use js so I need the JSON output like below. You can see this file on GitHub here.
How to get the array setup correctly?
The problem is JSON is output for the resourcify_sources, it's not actually outputting as an array of objects, it outputs the JSON with the actual index and then the values are array of index
So here's what I need the JSON output to look like:
{
"resourcify_count": 3,
"resourcify_count_title": null,
"resourcify_sources": [
{
"source_type": "source",
"source_title": "Source Title",
"source_url": "http://what.com"
},
{
"source_type": "resource",
"source_title": "Source Resource!",
"source_url": "http://sourceresource.com"
},
{
"source_type": "quote",
"source_title": "Quote Source",
"source_url": "http://quotesource.com"
}
]
}
Here's a var_dump of the $sources:
array (size=5)
'source_type' =>
array (size=5)
0 => string 'source' (length=6)
1 => string 'resource' (length=8)
3 => string 'source' (length=6)
4 => string 'resource' (length=8)
5 => string 'quote' (length=5)
'source_title' =>
array (size=5)
0 => string 'Source Title' (length=12)
1 => string 'Resource' (length=8)
3 => string 'SourceTWO' (length=9)
4 => string 'ResourceTWO' (length=11)
5 => string 'QuoteTWO' (length=8)
'source_url' =>
array (size=5)
0 => string 'http://what.com' (length=15)
1 => string 'resource.com' (length=12)
3 => string 'sourcetwo.com' (length=13)
4 => string 'resourcetwo.com' (length=15)
5 => string 'quotetwo.com' (length=12)
And here's the for loop I am using:
for ($i = 0; $i < $total_sources; $i++){
$source_type = $sources['source_type'][$i];
$source_title = $sources['source_title'][$i];
$source_url = $sources['source_url'][$i];
if ($source_url){
$source_url = esc_url_raw($source_url);
if (!$source_title) $source_title = $source_url;
$source_json['resourcify_sources'][$i]['source_type'] = $source_type;
$source_json['resourcify_sources'][$i]['source_title'] = $source_title;
$source_json['resourcify_sources'][$i]['source_url'] = $source_url;
}
}