admin管理员组

文章数量:1415484

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 acplish.

Thanks!

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 acplish.

Thanks!

Share Improve this question edited Jul 25, 2013 at 0:13 Imran Subhani asked Jul 24, 2013 at 23:33 Imran SubhaniImran Subhani 1,1001 gold badge21 silver badges41 bronze badges 3
  • 3 You need to nest your appended arrays then in another one with "shop"=> as key. – mario Commented Jul 24, 2013 at 23:35
  • 2 Why would you expect that output if your PHP data structure doesn't match? – elclanrs Commented Jul 24, 2013 at 23:35
  • I need to use it with some JavaScript plugin where I need same structure. – Imran Subhani Commented Jul 24, 2013 at 23:36
Add a ment  | 

2 Answers 2

Reset to default 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
}

Have you tried:

$bcData['shop'][] = array(
   'title'=>get_the_title(),
);
echo json_encode($bcData);

本文标签: javascriptHow to encode JSON object from an array in phpStack Overflow