I have this JSON file,
How can I loop through it to create an array of the last values (Cooling_area) like
$coolingArea = [800,750,900,300,930,500,670,...];
I have this JSON file,
$coolingArea = [800,750,900,300,930,500,670,...];
A clever way of doing this I found while following an online tutorial. That is go to your console window and do a console.log on it then simply copy the data that you want to use. The only thing you probably have to do is delete the erroneous data that is copied over.
The map method can help you to achieve that.
// coolingData is an object containing the parsed JSON data
const coolingArea = coolingData.map(area => area["Cooling_Area"]);
// coolingArea ends up as an array, containing [800,750,900,300,930,500,670...]
I spoke too soon, is there a way to do this using PHP?
Sure, PHP also has a mapping function…
$file = file_get_contents('./cooling-areas.json');
$json = json_decode($file, true);
$coolingAreas = array_map(function($element) {
return $element['Cooling_Area'];
}, $json);
var_dump($coolingAreas);
https://php.net/manual/en/function.file-get-contents.php
https://php.net/manual/en/function.json-decode.php
https://php.net/manual/en/function.array-map.php
I’ve moved this thread over to the PHP forum, to help avoid any confusion.
In php, you first need to use file_get_contents to get a file and write it to a variable, and then foreach over it.
ok, got the array
using
$coolingData = file_get_contents("data/cooling-areas.json");
$cooler = json_decode($coolingData, true);
$coolingTitles = array_map(function($element) {
return $element['Title'];
}, $cooler);
var_dump($coolingTitles);
echo "<br>";
print_r($coolingTitles);
the result,
array(12) { [0]=> string(9) "Icebound." [1]=> string(12) "Ocean Breeze" [2]=> string(10) "Ice Tundra" [3]=> string(11) "Cool Beans." [4]=> string(11) "Blue Steel." [5]=> string(8) "Sub-Zero" [6]=> string(13) "Ice Ice Baby." [7]=> string(9) "The Frost" [8]=> string(14) "Broken Dreams." [9]=> string(10) "Chill Out." [10]=> string(10) "Ice Giant." [11]=> string(11) "Chill Zone." }
Array ( [0] => Icebound. [1] => Ocean Breeze [2] => Ice Tundra [3] => Cool Beans. [4] => Blue Steel. [5] => Sub-Zero [6] => Ice Ice Baby. [7] => The Frost [8] => Broken Dreams. [9] => Chill Out. [10] => Ice Giant. [11] => Chill Zone. )
so if its an array of strings, how do I get it in the format
["Icebound","Ocean Breeze","Ice Tundra",...]
my solution
$coolingTitles = array_map(function($element) {
return '"'.$element['Title'].'"';
}, $cooler);
echo "[".implode(",",$coolingTitles)."]";
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.