php
  • arrays
  • json
  • short
  • 2016-10-10 4 views 0 likes 
    0

    json urlPHP json 배열 정렬

    나는 챔피언 배열을 정렬하고 싶습니다. " 챔피언 -> 0 -> stats -> totalSessionsPlayed"로 분류하고 싶습니다.하지만 할 수 없습니다. 어떻게 배열을 짧게 할 수 있습니까?

    $url = 'https://tr.api.pvp.net/api/lol/tr/v1.3/stats/by-summoner/3800684/ranked?season=SEASON2016&api_key=RGAPI-2F65B634-F9C5-4DA7-A5E3-1D955D5D1E3B'; 
    $content = file_get_contents($url); 
    $arr = json_decode($content); 
    $sorted = sort(array_column($arr, 'totalSessionsPlayed')); 
    

    ı이 코드를 발견했지만 작동하지 않습니다. 사용자 정의 비교 함수와

    +1

    질문 본문에 관련 JSON을 포함하십시오. – Pete

    +2

    그것 전부는 아니지만. –

    +0

    * 관련 * JSON 만주세요. – Pete

    답변

    1

    사용 usort :

    $champions = $arr->champions; 
    // usort alters the input array, no need to assign 
    usort($champions , function($a, $b) { 
        // Will sort in descending order, for ascending, switch sides 
        return $b->stats->totalSessionsPlayed - $a->stats->totalSessionsPlayed; 
    }); 
    

    기본적으로, 당신은 챔피언 배열의 첫 번째 수준을 정렬하고 내부적으로 낮은 값을 비교해야합니다.

    배열에 totalSessionsPlayed 키가 없으므로 코드가 작동하지 않습니다.

    0

    이 정보가 도움이되기를 바랍니다.

    여기서는 첫 번째 Object에 대해 중첩 된 foreach 루프를 사용하고 두 번째 Object에 대해 두 번째 foreach 루프를 사용하고 있습니다. array_filter를 사용하면 빈 문자열/요소를 제거하는 데 도움이됩니다. 빈 요소가 있으면 false를 반환합니다. SORT 함수 성공시 TRUE를, 실패하면 FALSE를 반환합니다. 그래서 우리는 마지막 루프를 사용하여 정렬 된 결과를 표시했습니다.

    <?php 
    $url = 'https://tr.api.pvp.net/api/lol/tr/v1.3/stats/by-summoner/3800684/ranked?season=SEASON2016&api_key=RGAPI-2F65B634-F9C5-4DA7-A5E3-1D955D5D1E3B'; 
    $content = file_get_contents($url); 
    $arr = json_decode($content); 
    $champions = ($arr->champions); 
    foreach($champions as $champion){ 
        $champion_totalSessionsPlayed = $champion; 
    
        foreach($champion_totalSessionsPlayed as $champions_totalSessionsPlayed){ 
         $totalSessionsPlayed = $champions_totalSessionsPlayed->totalSessionsPlayed; 
          $totalSessionsPlayed_array[] = $totalSessionsPlayed; 
        } 
    } 
    $totalSessionsPlayed = array_filter($totalSessionsPlayed_array); 
    sort($totalSessionsPlayed); 
    $arrlength = count($totalSessionsPlayed); 
    for($x = 0; $x < $arrlength; $x++) { 
        echo $totalSessionsPlayed[$x]; 
        echo "<br>"; 
    } 
    ?> 
    
    +2

    코드를 항상 설명하십시오. – Pete

    +0

    왜 downvote ??? 그냥 코드를 게시하기위한 ?? – VishalParkash

    +2

    답변에 대한 설명이 부족하기 때문입니다. 코드 전용 답변은 권장하지 않습니다. – Pete

     관련 문제

    • 관련 문제 없음^_^