3

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
3
  • 3
    You need to nest your appended arrays then in another one with "shop"=> as key. Commented Jul 24, 2013 at 23:35
  • 2
    Why would you expect that output if your PHP data structure doesn't match? Commented Jul 24, 2013 at 23:35
  • I need to use it with some JavaScript plugin where I need same structure. Commented Jul 24, 2013 at 23:36

2 Answers 2

6
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
Sign up to request clarification or add additional context in comments.

5 Comments

It outputs only: [{"shop":{"title":"Pink Nail Shop 9"}}] its inside a loop.
btw answer from miguelcaires is correct and it works like I want.
@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 another
@Imran You're welcome, if your problem exist yet, edit your question, and add complete your source code
0

Have you tried:

$bcData['shop'][] = array(
 'title'=>get_the_title(),
);
echo json_encode($bcData);
answered Jul 24, 2013 at 23:37

1 Comment

And have you? The index "shop" is at the wrong spot in your code.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.