数组总是返回null如何停止此操作


array always returns null how to stop this

我有一个php脚本,它使用curl来获取json提要的内容。在我尝试返回json提要中的"q"值之前,一切都很好。下面的代码只返回"null"。我该怎么解决这个问题?我怀疑这与线路$search_term = $term[$number]->q;有关,但我不能百分之百确定。

$lmgtfy_json_feed = get_data('http://live.com/');
$lmgtfy_search_term = json_decode($lmgtfy_json_feed);
$number = rand(0, count($lmgtfy_search_term)-1);
$search_term = $lmgtfy_search_term[number]->q;
echo json_encode($search_term);

您正在使用完整的数组$number作为$term的键。

如果您想从数组$term中选择一个随机元素,请使用PHP的rand函数,而不是创建和搅乱数组:

$number = rand(0, count($term)-1);
$search_term = $term[$number]->q;

只需使用

$term_item = $term[array_rand($term, 1)];
$search_term = (string)$term_item->q;

希望能有所帮助。