note 129803 added to function.json-encode

From: Date: Mon, 14 Oct 2024 15:42:53 +0000
Subject: note 129803 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-221592@lists.php.net to get a copy of this message
The Problem: --------------- When you filter an array in PHP using array_filter, the original keys are preserved. If you remove elements, you'll end up with gaps in the keys (non-consecutive). When encoded to JSON, this can lead to the list being interpreted as a JSON object instead of a JSON array, which might not be what your JavaScript code expects. The Solution: --------------- The array_values() function is essential in this scenario. It re-indexes the array with consecutive numerical keys (0, 1, 2, ...), ensuring that the JSON output is always a well-formed array. Example: ---------- <?php // Use Case: Filtering a list and ensuring consistent JSON array output // Imagine you have a list of items and need to send a filtered version to a JavaScript frontend // using JSON. You want to ensure the filtered list is always received as a JSON array, // regardless of which items were removed. // Sample data: A list of items $items = [ "first", "second", "third", "fourth", "fifth" ]; // Items to remove from the list $itemsToRemove = ["second", "fourth"]; // Filter the list, keeping original keys (which become non-consecutive) $filteredItems = array_filter($items, function($item) use ($itemsToRemove) { return !in_array($item, $itemsToRemove); }); // Prepare data for JSON output $output_arr = [ "list" => $filteredItems ]; // Output 1: JSON with non-consecutive keys (becomes an object) echo "Output without array_values:\n"; echo json_encode($output_arr, JSON_PRETTY_PRINT) . "\n\n"; /* Output: { "list": { "0": "first", "2": "third", "4": "fifth" } } */ // Reset keys to be consecutive using array_values $output_arr['list'] = array_values($output_arr['list']); // Output 2: JSON with consecutive keys (remains an array) echo "Output with array_values:\n"; echo json_encode($output_arr, JSON_PRETTY_PRINT) . "\n"; /* Output: { "list": [ "first", "third", "fifth" ] } */ ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 2800:21e7:f040:6e23:974:df75:7638:a0bd) ---- Manual Page -- https://php.net/manual/en/function.json-encode.php Edit -- https://main.php.net/note/edit/129803 Del: integrated -- https://main.php.net/note/delete/129803/integrated Del: useless -- https://main.php.net/note/delete/129803/useless Del: bad code -- https://main.php.net/note/delete/129803/bad+code Del: spam -- https://main.php.net/note/delete/129803/spam Del: non-english -- https://main.php.net/note/delete/129803/non-english Del: in docs -- https://main.php.net/note/delete/129803/in+docs Del: other reasons-- https://main.php.net/note/delete/129803 Reject -- https://main.php.net/note/reject/129803 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221592) next »