0

I have a JSON result file that is decoded into an array of objects. I am using a Foreach to find the correct player and then wish to create an array with all the information under the correct player.

This is a snippet of the array of objects:

object(stdClass)#3 (1) {
  ["result"]=>
  object(stdClass)#4 (18) {
    ["players"]=>
    array(10) {
      [0]=>
      object(stdClass)#5 (24) {
        ["account_id"]=>
        int(72775718)
        ["player_slot"]=>
        int(0)
        ["hero_id"]=>
        int(46)
        ["item_0"]=>
        int(50)
        ["item_1"]=>
        int(139)
        ["item_2"]=>
        int(149)
        ["item_3"]=>
        int(147)
        ["item_4"]=>
        int(168)
        ["item_5"]=>
        int(116)
        ["kills"]=>
        int(26)
        ["deaths"]=>
        int(10)
        ["assists"]=>
        int(9)
        ["leaver_status"]=>
        int(0)
        ["gold"]=>
        int(1622)
        ["last_hits"]=>
        int(285)

There are several players in this, and I am using the account_id to find the correct player with:

foreach ($data_decoded->result->players as $val){
            if($val->account_id == $this->PlayerID){
                echo "found you!"."\n";
}

How do I then create an array with all of the subsequent results? For example, underneath the account_id, I would like to store all of that information (player_slot, hero_id, etc.) Do I need to use another foreach? If so I honestly don't know how to word it.

I have tried:

    foreach ($data_decoded->result->players as $val){
        if($val->account_id == $this->PlayerID){
            echo "found you!"."\n"; 
            foreach($val as $test){
                $dataarray=array($test);

            }

but this only adds the values that are on the same "level" (poor terminology) as $val, and not the subsequent values?

k4kuz0
  • 1,045
  • 1
  • 10
  • 24
  • `if($val->account_id == $this->PlayerID) $dataarray = (array) $val`? – PeeHaa Mar 10 '14 at 07:50
  • `$val` is an individual player object. You should be able to get `player_slot`, `hero_id`, etc as properties of `$val`. – Agi Hammerthief Mar 10 '14 at 07:51
  • @Peehaa oh wow. That was easy. Didn't know I could do that! Do you want to write that as an answer, and I can give you the credit for it? – k4kuz0 Mar 10 '14 at 07:53

1 Answers1

2

If you really want to change it into an array you can simply cast it:

if ($val->account_id == $this->PlayerID) {
    $dataarray = (array) $val;
}

Demo: https://eval.in/116967

Community
  • 1
  • 1
PeeHaa
  • 71,436
  • 58
  • 190
  • 262