1

I converted an array to JSON, how do I get the value of the slug from it?

{
  "230": {
    "term_id": 230,
    "name": "Executive Committee",
    "slug": "executive_committee",
    "term_group": 0,
    "term_taxonomy_id": 241,
    "taxonomy": "team_member_filter",
    "description": "",
    "parent": 0,
    "count": 1,
    "object_id": 1561,
    "filter": "raw"
  }
}

Of course the first value "230" is different for each instance. How do I access the "slug" value for each instance inside of my loop?

I originally had this array in $variable:

  Array ( 
   [230] => stdClass Object ( 
      [term_id] => 230
      [name] => Executive Committee 
      [slug] => executive_committee
      [term_group] => 0 
      [term_taxonomy_id] => 241 
      [taxonomy] => team_member_filter
      [description] =>
      [parent] => 0 
      [count] => 1 
      [object_id] => 1561 
      [filter] => raw 
   )   
)

Why does $variable['slug'] not return anything?

1
  • Can you show the actual code that you have? Commented Mar 11, 2016 at 18:22

1 Answer 1

2

Use json_decode() and then you can access like an array:

$items = json_decode($variable, true); // 'true' here makes the json an associative array
foreach($items AS $item) {
    echo $item['slug']; // because it is associative  you can access each value by name
}

This echos executive_committee for the JSON you provided above.


From the original array ($variable)you would do the same thing:

foreach($variable AS $item) {
    echo $item->slug; // because you have an object, not an array 
}
Sign up to request clarification or add additional context in comments.

14 Comments

I was actually using json_encode from the original array because $item['slug'] was not returning anything. How do I make the original array associative?
You original array was associative to begin with. If you'd like to edit your post above, adding your original array, I'll edit my answer.
Cool - guess what? The same foreach() code will work! ¯\_(ツ)_/¯
ha, $item['slug'] is not returning anything for me. It is inside of the default wordpress loop. If I just print_r $items, the array for each post gets printed. But as soon as I add ['slug'], I get nothing
It is because slug is nested within the array item. You have to loop through $variable.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.