문제

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