JSON,获取第一个结果而不是最后一个结果 [英] JSON, get first result instead of last one
问题描述
我有一个带有很多结果的JSON,它包含在各种对象"中,这也与图像有关.
I have a JSON with a lot of results which contains in the various "objects", also this one related to images.
"image":[
{
"#text":"http:\/\/BLAHBLAH",
"size":"small"
},
{
"#text":"http:\/\/BLAHBLAH",
"size":"medium"
},
{
"#text":"http:\/\/BLAHBLAH",
"size":"large"
}
]
使用
$image = array_reduce($track['image'], function ($image, array $i) {
return $image ?: ($i['size'] == 'medium' ? $i['#text'] : null);
});
我得到中等的图像URL,尽管当我执行echo $image
时(按时间顺序)我得到循环中第一个结果的图像(JSON的底部)
I get the medium image URL, though when I do echo $image
I get the image of the first result (chronologically) in the loop (so bottom of JSON)
如何获取最新的(按时间顺序)(JSON顶部的第一个结果)?
How do I get the latest (chronologically) instead (first result at the top of the JSON)?
此处是整个代码. 这是链接(您可以在右下角看到相关部分).
Here's the whole code. Here's the link (you can see the relevant portion at the bottom right).
推荐答案
据我了解,您是第一个使用==中号的人
From what I understand you are after the first one with a size == medium
这是一个可以为您提供帮助的功能.
Here is a function that will get it for you.
function getTextForSize($array, $size = "medium") {
foreach($array as $v){
if ($v["size"] == $size){
return $v["#text"];
}
}
}
使用只是说
$text = getTextForSize($track["image"], "medium");
如果您要使用其他尺寸的图像,请更改第二个参数.
change the second argument if you want a different sized image.
如果您已嫁给array reduce方法,请尝试一下
If you are married to the array reduce method then try this out
$image = array_reduce($track['image'], function ($image, array $i) {
return $image.((!$image) && $i['size'] == 'medium' ? $i['#text'] : null);
}
);
如果您只是在第一个元素之后,就可以这样做.
If you are after just the first element can simply do this.
$track['image'][0]
如果您想输入文字,
$track['image'][0]['#text'];
尺寸为
$track['image'][0]['size'];
这篇关于JSON,获取第一个结果而不是最后一个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!