development

JSON 객체가 아닌 JSON 배열로 json_encode 스파 스 PHP 배열

big-blog 2020. 7. 27. 07:18
반응형

JSON 객체가 아닌 JSON 배열로 json_encode 스파 스 PHP 배열


PHP에는 다음과 같은 배열이 있습니다.

Array
(
    [0] => Array
        (
            [id] => 0
            [name] => name1
            [short_name] => n1
        )

    [2] => Array
        (
            [id] => 2
            [name] => name2
            [short_name] => n2
        )
)

JSON을 JSON 배열로 인코딩하여 다음과 같은 문자열을 생성하려고합니다.

[  
    {  
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    {  
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
]

그러나이 json_encode배열을 호출 하면 다음과 같은 결과가 나타납니다.

{  
    "0":{  
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    "2":{  
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
}

이것은 배열 대신 객체입니다.

json_encode대신 배열을 배열로 인코딩하려면 어떻게 해야합니까?


이 키가 - 당신은 당신의 배열이 연속하지 않기 때문에이 동작을 관찰하는 0하고 2있지만이없는 1키로.

숫자 인덱스만으로는 충분하지 않습니다. json_encodePHP 배열이 순차적 인 경우, 즉 키가 0, 1, 2, 3, ... 인 경우에만 PHP 배열을 JSON 배열로 인코딩합니다.

You can reindex your array sequentially using the array_values function to get the behaviour you want. For example, the code below works successfully in your use case:

echo json_encode(array_values($input)).

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

$indexedOnly = array();

foreach ($associative as $row) {
    $indexedOnly[] = array_values($row);
}

json_encode($indexedOnly);

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]

json_decode($jsondata, true);

true turns all properties to array (sequential or not)


Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

참고URL : https://stackoverflow.com/questions/11195692/json-encode-sparse-php-array-as-json-array-not-json-object

반응형