user1157393
user1157393

Reputation:

Convert JSON String into variables to echo out

I have the following JSON string:

[{\"index\":0,\"date\":\" 20120030\",\"title\":\"afsa\"}]

And I need to get out the contents into a variable foreach one.

This is how it is picked up so far...

 $json_data_string = $_POST['hidden_event']; // sanitize however
 $array_data = json_decode($json_data_string);

 echo $json_data_string;

I need to be able to echo each out. for example:

 foreach {
   echo $date;
   echo $title;
 }

Thanks in advance for any help.

Upvotes: 1

Views: 4705

Answers (5)

li-on
li-on

Reputation: 539

You can use extract function on $array_data to get variables.

$array_data = json_decode($json_data_string); 
extract($array_data); 
echo $index; 
echo $date;

Upvotes: 1

Mathieu
Mathieu

Reputation: 5695

foreach($array_data as $data) {
  echo $data->date, PHP_EOL;
  echo $data->title, PHP_EOL;
}

Upvotes: 2

FrontEnd Expert
FrontEnd Expert

Reputation: 5803

I think if you want to use this using jquery you will do like this:-

var recordList = [{\"index\":0,\"date\":\" 20120030\",\"title\":\"afsa\"}]

jQuery.each(recordList, function()
{
    alert(this.Name); // For example
    alert(this.date); // For example
});

or like this:-

      $.ajax({
                          type: "POST",
                          url: URL,
                          cache:false,
                          data: values,
                          dataType:'json',
                          success: function(json)
           {
                                var date = json.date;
                                alert(date);
                                }       // end success function
                        });  

Upvotes: 2

Jeroen
Jeroen

Reputation: 13257

$json_string = $_POST['hidden_event'];
$array = json_decode ( $json_data_string);

extract ($array);

echo $date;
echo $title;

Upvotes: 0

raPHPid
raPHPid

Reputation: 567

Try var_dump (http://php.net/manual/en/function.var-dump.php), that will give you idea how $array_data is structured. If you do this

echo '<pre>';
var_dump($array_data);
echo '</pre>';

you get even prettier dump. From there it's farily easy to see how to echo variables.

Upvotes: 0

Related Questions