dbj44
dbj44

Reputation: 1998

How do you manipulate the output using json_encode?

How would I structure $array so that when I pass it to json_encode

$output = json_encode($array);

the output would be:

$output = [
  {apples:"33" ,oranges:"22"},
  {apples:"44" ,oranges:"11"},
  {apples:"55" ,oranges:"66"},
]

Are there any options I need to use to get the output I need? Or is it all about how I structure my PHP array?

Upvotes: 2

Views: 99

Answers (3)

you can pass with an array of associative arrays in json_encode($var).

$array = array (
array(
    'johan'=>'male',
    'age'=>'22'
),
array(
    'lucy'=>'female',
    'age'=>'24'
),
array(
    'donald'=>'male',
    'age'=>'28'
)

);

Upvotes: -1

Rizier123
Rizier123

Reputation: 59681

This should work for you:

  • [] = array
  • {} = object
  • key:value = key : value

<?php

    $array = [
          (object)["apples" => "33", "oranges" => "22"],
          (object)["apples" => "44", "oranges" => "11"],
          (object)["apples" => "55", "oranges" => "66"],
        ];


    echo $output = json_encode($array);

?>

Output:

[
    {
        "apples": "33",
        "oranges": "22"
    },
    {
        "apples": "44",
        "oranges": "11"
    },
    {
        "apples": "55",
        "oranges": "66"
    }
]

Upvotes: 3

CT14.IT
CT14.IT

Reputation: 1737

You will just need to pass an array of associative arrays to json_encode

$array = array (
    array(
        'apples'=>'33',
        'oranges'=>'22'
    ),
    array(
        'apples'=>'44',
        'oranges'=>'11'
    ),
    array(
        'apples'=>'55',
        'oranges'=>'66'
    )
);

Upvotes: 2

Related Questions