0

In order to access this data via ajax, how can I give each json encoded value a constant name?

 $data = array();
 foreach($query->result() as $row) {

     $data[$row->id] = $row->name;

    }

This returns json in this format:

{"12428":"Alpine 12\" Single-Voice-Coil 4-Ohm Subwoofer",}

The id (12428) is not constant and therefore, I have nothing constant to look for when trying to decode the data with ajax.

How can I change the php code to add a constant value foreach of the encoded json items?

2 Answers 2

4
$data = Array();
foreach($query->result() as $row) {
    $data[] = Array("id" => $row->id, "name" => $row->name);
}

Then, your JSON object looks like:

[{"id":"12428","name","Alpine 12\" Single-Voice-Coil 4-Ohm Subwoofer"}]

You can now loop through that array and get the id and name of each element.

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was hoping to accomplish. Thank you very much.
1

Who cares.

js> d = {"12428":"Alpine 12\" Single-Voice-Coil 4-Ohm Subwoofer"}
[object Object]
js> for (i in d)
{
  print(d[i]);
}
Alpine 12" Single-Voice-Coil 4-Ohm Subwoofer

1 Comment

Yes, hence the "js>". print() is specific to the REPL though.

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.