简体   繁体   中英

PHP Object oriented array output

I did not make the array myself, so I honestly have no clue of how to echo an specific variable in the array.

This is my code:

foreach($server_players as $data) {
    print_r($data);
}

Which outputs

SteamPlayer Object
(
    [clientPort:SteamPlayer:private] => 
    [connectTime:SteamPlayer:private] => 76.529731750488
    [extended:SteamPlayer:private] => 
    [id:SteamPlayer:private] => 0
    [ipAddress:SteamPlayer:private] => 
    [loss:SteamPlayer:private] => 
    [name:SteamPlayer:private] => Din yndlings Slyngel <3
    [ping:SteamPlayer:private] => 
    [rate:SteamPlayer:private] => 
    [realId:SteamPlayer:private] => 
    [score:SteamPlayer:private] => 0
    [state:SteamPlayer:private] => 
    [steamId:SteamPlayer:private] => 
)

var_dump output

object(SteamPlayer)[14]
  private 'clientPort' => null
  private 'connectTime' => float 6556.9243164062
  private 'extended' => boolean false
  private 'id' => int 0
  private 'ipAddress' => null
  private 'loss' => null
  private 'name' => string 'Alfred' (length=6)
  private 'ping' => null
  private 'rate' => null
  private 'realId' => null
  private 'score' => int 2
  private 'state' => null
  private 'steamId' => null

I want to take the player name of indevidual players, but i don't know how.

this is kinda what i want to do

foreach($server_players as $data) {
    echo "Player name: ".$data['name:SteamPlayer:private'];
}

Try this:

foreach($server_players as $data) {
  echo "Player name: ".$data->getName();
}

The above answers are in the correct path but as your output has indicated:

[name:SteamPlayer:private]

So you will need to find out if you have getters in the object OR you will have to change some of the fields to public.

If you cannot do either of those things, then there is no straightforward way to do this given the info you've provided.

You can try doing it like this

foreach($server_players as $data) {
    echo "Player name: ".$data->name;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM