My code looks like:
if ( $query->have_posts() ) {
$j = 1;
while ( $query->have_posts() ) {
$query->the_post();
$bcData[] = array(
'title'=>get_the_title(),
);
$j++;
}
echo json_encode($bcData);
} else {
// no posts found
}
$bcData array outputs(using print_r ):
Array (
[0] => Array ( [title] => Pink Nail Shop 9 )
[1] => Array ( [title] => Pink Nail Shop 8 )
)
When I encode this array to json (using json_encode), the newly created json looks like:
[{"title":"Pink Nail Shop 9"},{"title":"Pink Nail Shop 8"}]
While I need json like this:
[{"shop":{"title":"Pink Nail Shop 9"}},{"shop":{"title":"Pink Nail Shop 8"}}]
Hopefully this makes sense, as I've tried hard to articulate what I am trying to accomplish.
Thanks!
asked Jul 24, 2013 at 23:33
Imran Subhani
1,0821 gold badge21 silver badges41 bronze badges
2 Answers 2
if ( $query->have_posts() )
{
$bcData = array();
$j = 1;
while ( $query->have_posts() )
{
$query->the_post();
$bcData[] = array(
'shop' => array(
'title'=>get_the_title()
)
);
$j++;
}
echo json_encode($bcData);
} else {
// no posts found
}
answered Jul 24, 2013 at 23:35
DJafari
13.6k8 gold badges46 silver badges69 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Imran Subhani
It outputs only: [{"shop":{"title":"Pink Nail Shop 9"}}] its inside a loop.
Imran Subhani
btw answer from miguelcaires is correct and it works like I want.
DJafari
@Imran are you testing my code ? my code result is :
[{"shop":{"title":"Test 0"}},{"shop":{"title":"Test 1"}},{"shop":{"title":"Test 2"}}] your problem is anotherDJafari
@Imran You're welcome, if your problem exist yet, edit your question, and add complete your source code
Imran Subhani
Have you tried:
$bcData['shop'][] = array(
'title'=>get_the_title(),
);
echo json_encode($bcData);
answered Jul 24, 2013 at 23:37
miguelcaires
6841 gold badge4 silver badges5 bronze badges
1 Comment
Sven
And have you? The index "shop" is at the wrong spot in your code.
default
"shop"=>as key.