2

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?

1
  • json_enocde?? you might mean json_encode?? Commented Mar 2, 2015 at 15:43

3 Answers 3

3

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

2 Comments

Casting to object should be unnecessary, as JSON does not have indexed arrays, so any indexed PHP array will be rendered in JSON as an object anyway.
@TRiG Yes, but I wanted to show it clearly that {} is an object in json
2

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'
    )
);

Comments

-1

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'
)

);

Comments

Your Answer

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.