我有一个非常复杂的数组,我想将它转换为PHP有效数组,这样我就可以遍历这些值。
JS数组:
$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'});
修改
PHP循环:它应该是每个值的图像部分
for ($i = 0;$i < $test.length;$i++){
saveToDisk($test[$i]['image'],$i);
}
以上是否正确?我怎样才能读懂数值?
答案 0 :(得分:1)
您可以使用json_decode函数将json格式的字符串转换为PHP数组(如果您在没有第二个参数的情况下调用它,则使用对象,或者使用false)
$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'];
}
另外,为了将JavaScript对象转换为有效的JSON字符串,您应该使用JSON.strngify函数:
JSON.stringify(object); // <-- JavaScript function
答案 1 :(得分:0)
你可以使用json_decode
在PHP中阅读解析答案 2 :(得分:0)
您的“数组”代码看起来像PHP和Javascript语法之间的无效混合。它看起来应该更像:
$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'}]");
或者更好:
$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']
];