PHP 如何為 json_encode 移除 Array Index

PHP 與 JavaScript 串接經常回傳 JSON 格式,但是會遇到 PHP 的 Array 預設 Index (Assoc array key reference index) 都會有 1、2、3 ...,要怎麼移除這 Index 在傳給 JavaScript 呢?

PHP 如何為 json_encode 移除 Array Index

PHP 要移除 Array Index,等於就是只要 Array 的 Value 值,可以使用 array_values 的 Function。

要串接在任何層級,遇到此情況,都可以使用。

<?php 
$a = [
    1 => 'a',
    2 => 'b',
    3 => 'c',
    4 => [
        1 => 'aa',
        2 => 'bb',
        3 => 'cc',
    ]
];
print_r('$a: ' . json_encode($a)); // {"1":"a","2":"b","3":"c","4":{"1":"aa","2":"bb","3":"cc"}}
echo "\n";
print_r('$a: ' . json_encode(array\_values($a))); // ["a","b","c",{"1":"aa","2":"bb","3":"cc"}]
echo "\n";
print_r('$a[4]: ' . json_encode($a[4])); // {"1":"aa","2":"bb","3":"cc"}
echo "\n";
print_r('$a[4]: ' . json_encode(array\_values($a[4]))); // ["aa","bb","cc"]
echo "\n";
print_r('$a: ' . json_encode($a)); // {"1":"a","2":"b","3":"c","4":{"1":"aa","2":"bb","3":"cc"}}
echo "\n";
$a[4] = array_values($a[4]); // only [4] remove index
print_r('$a: ' . json_encode($a) . ' ([4] remove index)'); // {"1":"a","2":"b","3":"c","4":["aa","bb","cc"]}
echo "\n";

// $a: {"1":"a","2":"b","3":"c","4":{"1":"aa","2":"bb","3":"cc"}}
// $a: ["a","b","c",{"1":"aa","2":"bb","3":"cc"}]
// $a[4]: {"1":"aa","2":"bb","3":"cc"}
// $a[4]: ["aa","bb","cc"]
// $a: {"1":"a","2":"b","3":"c","4":{"1":"aa","2":"bb","3":"cc"}}
// $a: {"1":"a","2":"b","3":"c","4":["aa","bb","cc"]} ([4] remove index)
?>

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料