Reputation: 269
how can I iterate trough this JSON output and put just "hersteller" values into an array and print them out? Do I need just one for-loop-block or a nested for-loop with $i and $j?
[
{
"id": 2,
"hersteller": "bmw",
"modell": "{modell}",
"baujahr": "2015",
"artikelname": "nockenwelle",
"ekpreis": 149,
"verkpreis": 349,
"mengeverfuegbar": 8
},
{
"id": 3,
"hersteller": "audi",
"modell": "{modell}",
"baujahr": "2018",
"artikelname": "kotfluegel",
"ekpreis": 89,
"verkpreis": 249,
"mengeverfuegbar": 4
},
{
"id": 4,
"hersteller": "mercedes",
"modell": "{modell}",
"baujahr": "2019",
"artikelname": "getriebe",
"ekpreis": 299,
"verkpreis": 859,
"mengeverfuegbar": 3
}
]
Thank you :)
Upvotes: 2
Views: 77
Reputation: 269
With the help of "codeit" I did following which solved my problem:
$output = array();
$urlContents = file_get_contents(#Here is a URL to get the JSON value#);
$bestandspflegeArray = json_decode($urlContents, true);
$hersteller = array_column($bestandspflegeArray, 'hersteller');
for ($i=0; $i < count($hersteller); $i++) {
$output[] = $hersteller[$i];
}
echo json_encode($output);
Thank you :)
Upvotes: 0
Reputation: 1052
<?php
$json = '[
{
"id": 2,
"hersteller": "bmw",
"modell": "{modell}",
"baujahr": "2015",
"artikelname": "nockenwelle",
"ekpreis": 149,
"verkpreis": 349,
"mengeverfuegbar": 8
},
{
"id": 3,
"hersteller": "audi",
"modell": "{modell}",
"baujahr": "2018",
"artikelname": "kotfluegel",
"ekpreis": 89,
"verkpreis": 249,
"mengeverfuegbar": 4
},
{
"id": 4,
"hersteller": "mercedes",
"modell": "{modell}",
"baujahr": "2019",
"artikelname": "getriebe",
"ekpreis": 299,
"verkpreis": 859,
"mengeverfuegbar": 3
}
]';
//convert json to array json_decode(array, true)
//this true mean convert it to array instead of object
$array = json_decode($json, true);
//create new empty array
$hersteller = array();
//iterate
foreach($array as $key => $val){
if(isset($val['hersteller'])){
$hersteller[] = $val['hersteller'];
}
}
echo "<pre>";
//print the array
print_r($hersteller);
Upvotes: 0
Reputation: 111
$arr = json_decode($str, true); //converts JSON string into array
$arr_hersteller = array_column($arr, 'hersteller'); //returns an array containing "hersteller" values
Upvotes: 2