1

I have this json encode in the database, and i want just echo values name_r in foreach , how is it?

[{
    "name_r": "saeed",
    "units": ["salam", "11", "11", "khobe", "22", "22", "salam"],
    "price_change": ["33", "33", "33", "44", "44", "44"]
}, {
    "name_r": "salavat",
    "units": ["55", "55", "khobe", "66", "66"],
    "price_change": ["77", "77", "77", "88", "88", "88", "99", "99", "99"]
}]

this my php, that have error(Message: Undefined index: name_r - Line Number: 179):

$query = $this->db->query("SELECT * FROM table ORDER BY id desc");
    $data = array();
    foreach ($query->result() as $row)
    {
        $data[] = json_decode($row->residence,true);
        echo $data["name_r"].'<br>'; //Line Number: 179
    }
1
  • Does the residence column contain the posted JSON data? Commented Sep 18, 2011 at 14:58

3 Answers 3

3

Assuming that the json_encoded data you provided is stored in one row of the database, the json_decode will give you an array of arrays. To echo all the name_r fields, you would need to:

foreach ($query->result() as $row){
    $data = json_decode($row->residence,true);
    foreach($data as $datum){
        echo $datum['name_r'];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You used [] in your assignment. This means that the result of the json_decode will be pushed at the end of your array.

Using var_dump($data) should help you understand what your array actually looks like, and solve your problem by yourself.

Comments

0

Assuming the example JSON you showed is data from a single record. The data is an array of objects, so you'll need an inner loops that loops over the array from each returned record.

foreach ($row->residence as &$value) {
    $data = json_decode($value,true);
    echo $data["name_r"].'<br>';
}

I am not a PHP dev, so I am unsure if my syntax is right. But hopefully you get the idea.

Comments

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.