Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP arrays be outputed to JSON format

Tags:

json

php

PHP arrays

$grades = array( array( name => "tom", 
                  grade => 'A'

                ),
           array( name => "jeff", 
                  grade=> 'B'

                ),
           array( name => "lisa", 
                  grade => 'C'
                )
         );

$output=array
(  'status'=>'ok',
   'content'=>$grades
)

And the final JSON output I want to see would be {"status":'ok',"content":"{"tom":"A","jeff":"B","lisa":"B"}"}

The question is how should I manipulated the array so it can give me the final output like above JSON? would json_encode($output); echo $output do the trick? or
Do I have to do

json_encode($grades) then another json_encodes($output) but I am seeing extra \ thing like {"status":1,"content":"{\"tom\":\"A\",\"jeff\":\"B\",\"lisa\":\"B\"}"}

like image 893
lilzz Avatar asked Dec 22 '22 07:12

lilzz


2 Answers

Try this simple command

$my_array = [
    "test" => "value", 
    "another" => [
        "fruits" => ["Apple", "Orange"]
    ]
];

print_r(json_encode($my_array));

It will produce

{
    "test":"value",
    "another":{
        "fruits":["Apple","Orange"]
    }
}
like image 82
Aditya Kresna Permana Avatar answered Dec 24 '22 00:12

Aditya Kresna Permana


I don't understand why you don't write just this:

<?php
$grades = array(
    array(
        'name' => 'tom',
        'grade' => 'A'
    ),

    array(
        'name' => 'jeff',
        'grade' => 'B'
    ),

    array(
        'name' => 'lisa',
        'grade' => 'C'
    ),
);

$output = array(
    'status'  => 'ok',
    'content' => $grades,
);

print_r(json_decode(json_encode($output)));

It prints:

stdClass Object
(
    [status] => ok
    [content] => Array
        (
            [0] => stdClass Object
                (
                    [name] => tom
                    [grade] => A
                )

            [1] => stdClass Object
                (
                    [name] => jeff
                    [grade] => B
                )

            [2] => stdClass Object
                (
                    [name] => lisa
                    [grade] => C
                )

        )

)

Isn't is the expected result?

like image 40
Alessandro Desantis Avatar answered Dec 24 '22 00:12

Alessandro Desantis