我正在使用下面的数组,并希望询问我应该如何在' match_id'中访问/引用值?和' match_comp_ID'?
我需要以两种方式引用它:问题1:首先在foreach声明中。这已在下面得到解答:
foreach $jason_a['matches'] as $match {
echo $match['match_id']
echo $match['match_comp_id']
}
问题2:我想通过使用sort函数对这两个键的输出进行排序,我将通过usort调用它:
function cmp($a, $b)
{
// sort by match_id
$retval = strnatcmp(substr($b->match_id,0,10), substr($a->match_id,0,10));
// if identical, sort by match_comp_id
if(!$retval) $retval = strnatcmp($a->match_comp_id, $b->match_comp_id);
return $retval;
}
usort($json_a, "cmp");
在排序功能中使用match_id
或$json['match_id]
格式无法正常工作。我不知道该搜索什么。
数组是:
array(4) {
["APIRequestsRemaining"]=> int(920)
["matches"]=> array(3) {
[0]=> array(3) {
["match_id"]=> string(7) "1999477"
["match_static_id"]=> string(7) "1755895"
["match_comp_id"]=> string(4) "1204" }
[1]=> array(3) {
["match_id"]=> string(7) "1999478"
["match_static_id"]=> string(7) "1755891"
["match_comp_id"]=> string(4) "1204" }
[2]=> array(3) {
["match_id"]=> string(7) "1999479"
["match_static_id"]=> string(7) "1755894"
["match_comp_id"]=> string(4) "1204" }
}
["Action"]=> string(5) "today"
["Params"]=> array(4) {
["Action"]=> string(5) "today"
["APIKey"]=> string(31) "xxxx-xxxx-xxxx-xxxx"
["OutputType"]=> string(4) "JSON"
["comp_id"]=> string(4) "1204"
}
php手册指出:
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type
。我认为这是我的问题。但是如果数组不能用作键,那么我该如何访问这个键值呢?
答案 0 :(得分:2)
foreach ($json_a['matches'] as $match) {
// do something with $match['match_id'] and $match['match_comp_id']
}
对于你问题的第2部分,你真的想要通过'匹配'子数组到你的排序函数:
$matches = $json_a['matches'];
usort($matches, 'cmp');
// now the $matches array should be sorted according to rules in function cmp()