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?

3
  • if($val->account_id == $this->PlayerID) $dataarray = (array) $val? Commented Mar 10, 2014 at 7:50
  • $val is an individual player object. You should be able to get player_slot, hero_id, etc as properties of $val. Commented Mar 10, 2014 at 7: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? Commented Mar 10, 2014 at 7:53

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.