質問

So i have the following array structure:

{
"_": {
    "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
            },

            [...]

And i want to search for a "sub array" where the value "championId" = x and statType = y. I would then have the [x] if that array, and i should then be able to return any value in that array.

here is some of the PHP code i currently have:

$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; 
    } 
} 

As additional information then i am using $response = Unirest::get to get the array.

EDIT with full code:

$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;
役に立ちましたか?

解決

You found the answer, however needs some tweaks.

$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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top