2

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 :)

Mikhail Prosalov
  • 4,155
  • 4
  • 29
  • 41
volkanb
  • 229
  • 3
  • 14
  • Does this answer your question? [php: loop through json array](https://stackoverflow.com/questions/4731242/php-loop-through-json-array) – wazelin Jan 09 '20 at 11:17

3 Answers3

2
$arr = json_decode($str, true);  //converts JSON string into array
$arr_hersteller = array_column($arr, 'hersteller'); //returns an array containing "hersteller" values
codeit
  • 111
  • 8
0
<?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);
Akam
  • 1,089
  • 16
  • 24
0

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 :)

volkanb
  • 229
  • 3
  • 14