How can you extract specific values from a JSON object and store them in a new array using PHP?
To extract specific values from a JSON object and store them in a new array using PHP, you can first decode the JSON object using `json_decode()`, access the specific values using their keys, and then store those values in a new array. This can be achieved by looping through the decoded JSON object and selecting only the desired values to be stored in the new array.
$jsonObject = '{"key1": "value1", "key2": "value2", "key3": "value3"}';
$decodedObject = json_decode($jsonObject, true);
$newArray = array();
$keysToExtract = array("key1", "key3");
foreach($keysToExtract as $key) {
if(isset($decodedObject[$key])) {
$newArray[$key] = $decodedObject[$key];
}
}
print_r($newArray);
Keywords
Related Questions
- What are the steps required to access Facebook likes using the Graph API in PHP?
- How can PHP sessions be used to store not only user login status but also user roles for access control?
- In PHP development, what resources or documentation should be consulted to address errors related to reserved keywords like 'alter' in MySQL queries, and how can these issues be resolved effectively?