0

所以我有以下数组结构:

{
"_": {
    "APP_ID": "server_tracked"
},
"success": true,
"requestTime": "2013-09-14T15:05:28-07:00",
"shard": "North_America:OTg0ZGYzNjA0OGYxNjAyNWUzZjVlNTQwZDk4YTdjNTYzMGE3NTA4Ng",
"player": {
    "accountId": xxx,
    "summonerId": xx,
    "name": "xx",
    "icon": xx,
    "internalName": "xx",
    "level": xx
},
"data": {
    "lifetimeStatistics": {
        "array": [
            {
                "count": 1,
                "statType": "TOTAL_SESSIONS_PLAYED",
                "dataVersion": 0,
                "value": 1,
                "championId": 111,
                "futureData": null
            },
            {
                "count": 0,
                "statType": "TOTAL_SESSIONS_LOST",
                "dataVersion": 0,
                "value": 0,
                "championId": 111,
                "futureData": null
            },

            [...]

我想搜索一个“子数组”,其中值“championId”= x 和 statType = y。如果该数组,我将拥有 [x],然后我应该能够返回该数组中的任何值。

这是我目前拥有的一些 PHP 代码:

$result = json_decode($response -> raw_body);

$array = $result->data->lifetimeStatistics->array;

$search1 = x;
$search2 = y;  

$cluster=false; 
foreach ($array as $n=>$c) { 
    if (in_array($search, $c)) { 
        $cluster=$n; break; 
    } 
} 

作为附加信息,我将使用$response = Unirest::get它来获取数组。

编辑完整代码:

$result = json_decode($response -> raw_body);

$haystack = $result->data->lifetimeStatistics->array;

$searchx = x;
$searchy = y;

$arrayNumber = null;
foreach ($haystack as $n=>$c) { 
    if ($c->championId === $searchx && $c->statType === $searchy) {
        $arrayNumber = $n;
    } 
} 

// We now get the value from that array

$array = $result->data->lifetimeStatistics->array[$arrayNumber]->value;
return $array;
4

1 回答 1

0

您找到了答案,但需要进行一些调整。

$result = json_decode($response -> raw_body);

$haystack = $result->data->lifetimeStatistics->array;

$searchx = "x"; // fill as required
$searchy = "y"; // fill as required

$cluster=null;
foreach ($haystack as $n=>$c) { 
    if ($c["championId"] === $searchx && $c["statType"] === $searchy) {
        $cluster=$n; break; 
    } 
} 
if (is_null($cluster)) die("Not found?!"); //do whatever you want if not found
于 2013-09-14T23:11:55.107 回答