채택완료

json 데이터 가공 질문 드립니다.

json 데이터를 가공해 DB에 넣거나 화면에 표시하려고
api+json으로 받은 데이터를 json_decode하였는데
이후 데이터를 꺼내 쓰는 방법을 모르겠습니다.

밑에 출력 결과를
foreach($player as $key => $value ){
echo '$key => $value'. '<br />';
}
를 하면 화면에 아무것도 표시되지 않더라구요.

var_dump($player);
출력 결과

 

받은 데이터
object(Pubg\Object\Player)#32 (3) {
  ["id":protected]=>
  string(40) "account.aa28ebaf6f4f4b88a7bd4b415d22222b"
  ["name":protected]=>
  string(8) "taemin98"
  ["data":protected]=>
  array(5) {
    ["type"]=>
    string(6) "player"
    ["id"]=>
    string(40) "account.aa28ebaf6f4f4b88a7bd4b415d22222b"
    ["attributes"]=>
    array(7) {
      ["titleId"]=>
      string(13) "bluehole-pubg"
      ["shardId"]=>
      string(5) "steam"
      ["createdAt"]=>
      string(20) "2020-07-24T14:19:00Z"
      ["updatedAt"]=>
      string(20) "2020-07-24T14:19:00Z"
      ["patchVersion"]=>
      string(0) ""
      ["name"]=>
      string(8) "taemin98"
      ["stats"]=>
      NULL
    }
    ["relationships"]=>
    array(2) {
      ["assets"]=>
      array(1) {
        ["data"]=>
        array(0) {
        }
      }
      ["matches"]=>
      array(1) {
        ["data"]=>
        array(41) {
          [0]=>
          array(2) {
            ["type"]=>
            string(5) "match"
            ["id"]=>
            string(36) "8b91d5f2-7a21-41b8-a4ef-7dc86603f5e2"
          }
          [1]=>
          array(2) {
            ["type"]=>
            string(5) "match"
            ["id"]=>
            string(36) "00f360b4-6c25-4f4b-be17-2015dcaf6966"
          }
          [2]=>
          array(2) {
            ["type"]=>
            string(5) "match"
            ["id"]=>
            string(36) "6cf5f98f-e5d5-490e-9c7f-d478380c85b9"
          }
        }
      }
    }
    ["links"]=>
    array(2) {
      ["self"]=>
      string(95) "https://api.playbattlegrounds.com/shards/steam/players/account.aa28ebaf6f4f4b88a7bd4b415d22222b"
      ["schema"]=>
      string(0) ""
    }
  }
}

 

Copy
소스코드

 

호출

 

$api = new Pubg\Api($PUBGconfig);

$playername1='taemin98';

$playerService = new Pubg\Player($api);

$player = $playerService->get($playername1);

 

//get 함수

public function get($playerName)

    {

        if (strpos($playerName, 'account.') !== false) {

            $data = $this->api->request(sprintf('/shards/{platform}/players/%s', $playerName))['data'];

        } else {

            $data = $this->api->request(sprintf("/shards/{platform}/players?filter[playerNames]=%s", $playerName))['data'][0];

        }

 

        return $this->populate($data);

    }

 

 

//populate 함수

    public function populate($data)

    {

        $player = new PlayerObject();

 

        $player->setId($data['id']);

        $player->setName($data['attributes']['name']);

        $player->setData($data);

 

        return $player;

    }

 

//request 함수

    public function request($path)

    {

        $endpoint = str_replace('{platform}', $this->PUBGconfig->getPlatform(), self::API_URL . $path);

 

        $client = new \GuzzleHttp\Client();

 

        $response = $client->request('GET', $endpoint, [

            'headers' => [

                'Authorization' => sprintf('Bearer %s', $this->PUBGconfig->getApiKey()),

                'Accept' => 'application/vnd.api+json'

            ]

        ]);

 

        return json_decode($response->getBody()->getContents(), true);

    }
|

답변 1개 / 댓글 3개

채택된 답변
+20 포인트
한 플레이어의 정보를 담고 있는데 왜 반복문을 사용하시는지요?
$player->setData($data); 데이터가 json_decode 파일로 추정됩니다 
foreach($player->getData() as $key => $value ){
echo '$key => $value'. '<br />';
}
로 한번 해보시기 바랍니다.

//populate 함수
    public function populate($data)
    {
        $player = new PlayerObject();
 
        $player->setId($data['id']);
        $player->setName($data['attributes']['name']);
        $player->setData($data);
 
        return $player;
    }

답변에 대한 댓글 3개

PHP초보라서... 제가 이해도가 부족합니다.
활용하려고 방법을 공부 중입니다.
https://github.com/samiaraboglu/pubg-php-api 원본 소스 이고

말씀하신대로 하였더니
$key => $value
$key => $value
$key => $value
$key => $value
$key => $value 라고 값니 나옵니다.
https://www.php.net/manual/en/control-structures.foreach.php
echo에서 '(쉼표)안의 내용은 문자열로 취급하고 변수내용을 출력하실려면 "(따옴표) 를 사용해야됩니다.

답변을 작성하려면 로그인이 필요합니다.