json_decode/多维数组后访问JSON数组 [英] Accessing JSON array after json_decode/multidimensional array
问题描述
我从 Twitter api 中进行搜索,使用 file_get_contents 获取数据,然后传递给 json_decode,后者为我提供了这个数组结构.
I'm pulling in a search from the Twitter api, fetching the data with file_get_contents and then passing to json_decode which give me this array structure.
{"results":[
{
"from_user":"A-user-name",
"from_user_id":457304735,
"text":"Ich R U #BoysNoize #SuperRola",
"entities":{
"urls":[{
"url":"http:\/\/t.co\/WZnUf68j",
"expanded_url":"http:\/\/instagr.am\/p\/Vz4Nnbnjd6\/",
}]
}]
]
这对拉取的每条推文都会重复,现在我可以使用 foreach 循环访问用户名和文本并将结果的每个实例分配给一个变量,然后从该变量中提取数据.
This repeats for every tweet pulled, Now I can access the user name and text using a foreach loop and assigning every instance of results to a variable, then pulling data from the variable.
foreach($jsonArr['results'] as $item){
// Takes the Array jsonArr and for every results heading creates an $item
$user = mysql_real_escape_string($item['from_user']);
$text = mysql_real_escape_string($item['text']);
这可以保存正确的变量,但是我似乎无法在结果中获取实体数组中的数据.如果我打印出像用户名或文本这样的实体变量
This saves the correct variables OK, But I can't seem to get the the data within the entities array within the results. If I print out the Entities var like the username or text I get
ArrayArrayArrayArrayArrayArrayArrayArrayArrayArray
所以它保存了返回的每个结果的数组,但我到底如何访问它,我一直在使用我知道的其他一些访问数组数据的方法,但它们似乎都失败了.任何有关如何获取这些值或将它们与 foreach 集成的帮助将不胜感激
So It holds the arrays for each results returned but how on earth do I access it, I've been messing around with a few other methods I know for accessing array data but they all seem to fall flat. Any help with how to get at these values, or integrate them with the foreach would be greatly appreciated
推荐答案
假设您选择将 JSON 解码为多维数组,而不是对象:
Assuming that you've chosen to decode the JSON as a multi-dimensional array, rather than as objects:
foreach ($results as $tweet) {
$user = $tweet["from-user"];
$text = $tweet["text"];
$entities = $tweet["enities"];
$urls = $entities["urls"];
foreach ($urls as $url) {
echo $url["expanded_url"];
}
}
等等
这篇关于json_decode/多维数组后访问JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!