Reputation: 1605
I have a very complicated array, and i want to convert it into a PHP valid array so i can loop through the values.
JS array:
$test = ( // Portraits
{'image'=> 'http://farm8.staticflickr.com/7319/8993158058_f82968e61a_b.jpg', 'thumb'=> 'http://farm8.staticflickr.com/7319/8993158058_f82968e61a_t.jpg'},
{'image'=> 'http://farm3.staticflickr.com/2891/8993155214_b8e091c625_b.jpg', 'thumb'=> 'http://farm3.staticflickr.com/2891/8993155214_b8e091c625_t.jpg'},
{'image'=> 'http://farm8.staticflickr.com/7432/8993133146_d647438c55_b.jpg', 'thumb'=> 'http://farm8.staticflickr.com/7432/8993133146_d647438c55_t.jpg'});
EDIT
PHP loop: it should the image part for every value
for ($i = 0;$i < $test.length;$i++){
saveToDisk($test[$i]['image'],$i);
}
Is the above correct? how can i read through the values?
Upvotes: 0
Views: 52
Reputation: 4962
You can use json_decode function to convert json formatted string into a PHP arrays (or object if you're calling it without the second parameter or with false instead)
$test = '[{"image":"http:\/\/farm8.staticflickr.com\/7319\/8993158058_f82968e61a_b.jpg","thumb":"http:\/\/farm8.staticflickr.com\/7319\/8993158058_f82968e61a_t.jpg"},{"image":"http:\/\/farm3.staticflickr.com\/2891\/8993155214_b8e091c625_b.jpg","thumb":"http:\/\/farm3.staticflickr.com\/2891\/8993155214_b8e091c625_t.jpg"},{"image":"http:\/\/farm8.staticflickr.com\/7432\/8993133146_d647438c55_b.jpg","thumb":"http:\/\/farm8.staticflickr.com\/7432\/8993133146_d647438c55_t.jpg"}]';
$array = json_decode($test, 1);
// Looping each inner array and printing image/thumb keys
foreach ($array as $arr) {
echo $arr['image'].' - '.$arr['thumb'];
}
Also in order to convert your JavaScript object to a valid JSON string you should be using the JSON.strngify function:
JSON.stringify(object); // <-- JavaScript function
Upvotes: 1
Reputation: 41837
Your "array" code looks like an invalid mixture between PHP and Javascript syntax. It should look more like:
$test = json_decode("[
{'image'=> 'http://farm8.staticflickr.com/7319/8993158058_f82968e61a_b.jpg', 'thumb'=> 'http://farm8.staticflickr.com/7319/8993158058_f82968e61a_t.jpg'},
{'image'=> 'http://farm3.staticflickr.com/2891/8993155214_b8e091c625_b.jpg', 'thumb'=> 'http://farm3.staticflickr.com/2891/8993155214_b8e091c625_t.jpg'},
{'image'=> 'http://farm8.staticflickr.com/7432/8993133146_d647438c55_b.jpg', 'thumb'=> 'http://farm8.staticflickr.com/7432/8993133146_d647438c55_t.jpg'}]");
Or better yet:
$test = [
['image'=> 'http://farm8.staticflickr.com/7319/8993158058_f82968e61a_b.jpg', 'thumb'=> 'http://farm8.staticflickr.com/7319/8993158058_f82968e61a_t.jpg'],
['image'=> 'http://farm3.staticflickr.com/2891/8993155214_b8e091c625_b.jpg', 'thumb'=> 'http://farm3.staticflickr.com/2891/8993155214_b8e091c625_t.jpg'],
['image'=> 'http://farm8.staticflickr.com/7432/8993133146_d647438c55_b.jpg', 'thumb'=> 'http://farm8.staticflickr.com/7432/8993133146_d647438c55_t.jpg']
];
Upvotes: 0