创建数组从对象php


Create array from objects php

我有一个JSON结果文件,它被解码成一个对象数组。我使用Foreach来找到正确的player,然后希望在正确的播放器下创建一个包含所有信息的数组。

这是对象数组的一个片段:
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)

有几个players在这,我使用account_id找到正确的球员:

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

如何创建一个包含所有后续结果的数组?例如,在account_id下面,我想存储所有这些信息(player_slot, hero_id等),我需要使用另一个foreach吗?如果是的话,我真的不知道该怎么说。

I have try:

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

,但这只会添加与$val在同一"级别"(糟糕的术语)上的值,而不是随后的值?

如果你真的想把它变成一个数组,你可以简单地强制转换它:

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

演示:https://eval.in/116967