سؤال

I want to have this JSON output;

                          [
                            {c: [
                                {v: "1"},
                                {v: 90}
                            ]},
                            {c: [
                                {v: "2"},
                                {v: 80}
                            ]}
                          ] 

This is my php code;

            $data = array('c' => ( array('v'=>1 ), array('v'=>90 ) ),
                                 ( array('v'=>2 ), array('v'=>80 ) )
                    );
            echo json_encode($data);

The syntax is not even right and I have spent some time adding brackets here and there but the error is still there. How to get the right php array to achieve the desired json output?

Thank you very much.

هل كانت مفيدة؟

المحلول

You should recreate the array like this to get the expected JSON.

<?php

$arr = array(
    0 =>
        array(
            'c' =>
                array(
                    0 =>
                        array(
                            'v' => '1',
                        ),
                    1 =>
                        array(
                            'v' => 90,
                        ),
                ),
        ),
    1 =>
        array(
            'c' =>
                array(
                    0 =>
                        array(
                            'v' => '2',
                        ),
                    1 =>
                        array(
                            'v' => 80,
                        ),
                ),
        ),
);

echo json_encode($arr);

OUTPUT :

[{"c":[{"v":"1"},{"v":90}]},{"c":[{"v":"2"},{"v":80}]}]

نصائح أخرى

<?php

$data = array(
    'c' => array(
            array('v' => 1), 
            array('v' => 90,) 
    ),
    'd' => array(
            array('v' => 2), 
            array('v' => 90,) 
    ),
);

echo json_encode($data);

Output as you wanted, only second 'c' changed to 'd': {"c":[{"v":1},{"v":90}],"d":[{"v":2},{"v":90}]}

enclose the array with array to get the [ notation

<?php
$data = array(array('c' => array(array('v'=>1 ),array('v'=>90 )) ,array(array('v'=>2 ,array('v'=>80 )) )));
echo json_encode($data);

output:

[{"c":[{"v":1},{"v":90}],"0":[{"v":2,"0":{"v":80}}]}]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top