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_encode
PHP 배열이 순차적 인 경우, 즉 키가 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));
?>
'development' 카테고리의 다른 글
중첩 된 try catch 블록을 피하기위한 패턴? (0) | 2020.07.27 |
---|---|
다른 컨트롤러에서 동작으로 리디렉션 (0) | 2020.07.27 |
Sqlite : CURRENT_TIMESTAMP는 시스템 시간대가 아닌 GMT입니다. (0) | 2020.07.27 |
ng-repeat로 함수가 반환 한 항목을 반복하는 방법은 무엇입니까? (0) | 2020.07.27 |
PostgreSQL-데이터베이스 이름 변경 (0) | 2020.07.27 |