Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a json string like this:

$fields_string = '
{"fields":
   {"customers":[{"name":"john","id":"d1"},
                 {"name":"mike","id":"d2"},
                 {"name":"andrew","id":"d3"},
                 {"name":"peter","id":"d4"}]
   }
}'

How can I print each name? I will use them later in a html select options, I know how to do that. But I couldn't get the string out. Here are something I tried:

$obj = json_decode($fields_string);
$fields_detail = $obj-?{"fields"}->{"customers"};

at this point, I am able to print the customer array out by echo json_encode($fields_detail), but before that, I want to get the name break down using foreach. I tried several times, it didn't work. Can anyone help please.

Thanks!

share|improve this question
 
You want to get what? How did you try? How did it not work? –  Jon Feb 21 '13 at 11:18
add comment

4 Answers

up vote 4 down vote accepted

Customers is an array of objects so iterating over each object and reading the property should work.

foreach ($fields_detail as $customer) {
  echo $customer->name;
}
share|improve this answer
 
@koopajah you missed the second fragment of code phpfiddle.org/lite/code/xr4-8tz –  Maks3w Feb 21 '13 at 11:26
 
I see what I have done wrong. This is just it. Thank you very much! –  the_summer_bee Feb 21 '13 at 11:43
add comment

Something like this:

$data = json_decode($fields_string, true); // return array not object
foreach($data['fields']['customers'] as $key => $customer) {
 echo $customer['name']; 
}
share|improve this answer
add comment
foreach($obj->fields->customers as $fields)
echo $fields->name;
share|improve this answer
add comment

Access the names via fields->customers:

$obj = json_decode($fields_string);

foreach($obj->fields->customers as $customer)
{
    echo $customer->name . "\n";
}

Demo

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.