Question

I have this json var from google api :

$json='
{
 "kind": "webfonts#webfontList",
 "items": [ 
{
   "kind": "webfonts#webfont",
   "family": "Jockey One",
   "variants": [
    "400"
   ],
   "subsets": [
    "latin",
    "latin-ext"
   ]
  },
  {
   "kind": "webfonts#webfont",
   "family": "Josefin Sans",
   "variants": [
    "100",
    "100italic",
    "300",
    "300italic",
    "400",
    "400italic",
    "600",
    "600italic",
    "700",
    "700italic"
   ],
   "subsets": [
    "latin"
   ]
  },
....
 ]
}';

How can i decode $json with php in order to display informations like this :

  • Font 1 : family - variant - subsets
  • Font 2 : family - variant - subsets

Ex for the second item :

  • Font family : Josefin Sans | variants : 100, 100italic,300...|subsets : latin

Thank you

Was it helpful?

Solution

$data = json_decode($json,true);
$items = $data['items'];
$i = 0;
foreach ($items as $item) {
    $i++;
    $str = 'Font '.$i.' '.$item['family'].' Subsets:';
    foreach ($item['variants'] as $variant) {
      $str .= ' '.$variant.' ';
    }
    $str.= ' Variants';
    foreach ($item['subsets'] as $subset) {
      $str .= ' '.$subset;
    }
    echo $str.'<br />';
}

This does exactly what you want.

OTHER TIPS

I think that the most comfortable way is to create a data structure in your PHP code, and you will decode this JSON to a list of items from this type. Then, it will be very easy to iterate this list and get the data that you want.

The data structure that I'm talking about is something that will contain

String : kind
String : family
List<String> : variants
List<String> : subsets

hope this helps...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top