Reputation: 2247
I have a javascript that contacts a php page which gets some data from a database and save it in an array.
I want to take that array and loop it out with jquery.
The array looks like this:
Array (
[0] => Array ( [image] => article_list1.png [title] => Everyone involved in OMS in Ghent )
[1] => Array ( [image] => article_list1.png [title] => Everyone involved in OMS in Ghent )
[2] => Array ( [image] => article_list1.png [title] => Everyone involved in OMS in Ghent )
[3] => Array ( [image] => article_list1.png [title] => Everyone involved in OMS in Ghent )
[4] => Array ( [image] => article_list1.png [title] => Everyone involved in OMS in Ghent )
[5] => Array ( [image] => article_list1.png [title] => Everyone involved in OMS in Ghent )
);
Upvotes: 0
Views: 431
Reputation: 17179
The best way to do this is to json_encode the array and then echo the result out to the JavaScript/jQuery:
Here is the PHP php demo
<?php
$myarray = Array (
Array ( 'image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent' ),
Array ( 'image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent' ),
Array ( 'image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent' ),
Array ( 'image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent' ),
Array ( 'image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent' ),
Array ( 'image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent' )
);
echo json_encode($myarray);
?>
This should give you something like this:
[{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"}]
and to access it using jQuery jsfiddle demo:
var myJson = '[{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"}]';
myJson = JSON.parse(myJson);
for(var i=0; i<myJson.length; i++)
console.log(myJson[i].image+ ' ' + myJson[i].title);
Upvotes: 2
Reputation: 22758
You could always use php To print that array as a js list. Or export it via json.
Upvotes: 0