How to retrieve value from returned object in php?

1.5k Views Asked by At

How to retrieve value from a complicated object structure in php? I know using '->' operator we can access the value but I am very confused in the object I am returned with. From the object returned, I want to fetch the character value. How do i do that? I am using Neo4jPHP and trying to execute a cypher query "MATCH (n) RETURN distinct keys(n)" to return all distinct property keys. After doing a var_dump of the row object, the partial output is shown below. see in image about the object structure

Edit:- My edited code after following Mikkel's advice:-

$keyquery="MATCH (n) RETURN distinct keys(n)"; 
$querykey=new Everyman\Neo4j\Cypher\Query($client, $keyquery);
$resultkey = $querykey->getResultSet();
foreach ($resultkey as $row) 
{
for($i=0;$i<count($row[0]);$i++)
{
echo $row[0][$i]; // returns all the property keys from the Row object
}
}
4

There are 4 best solutions below

1
On

The value you are looking for is protected and not accessible,

  1. try find object class and add function to retrieve the value.
  2. use regular expression to extract the portion, which is not recommended: /\'character\'(length\=(.*?))/
2
On

If you look the class Row you will find out that you can access it treating the object like an array.

$character = $myRow[0];
2
On

Looking at the object you dumped here, you can see that the object is implementing \Iterator, \Countable, \ArrayAccess, which means you can basically treat it like an array. The underlying data source is the protected $raw.

$queryResult = ...;

foreach ($queryResult as $row) {
   echo $row['character'] . PHP_EOL;
}
2
On

You can't access the object property directly as it was declared as protected (only accessible from within the class or an inheriting class).

However, in such a case, the developer has usually added an object method or overloading function that allows you to access the information you're looking for. Taking a peek at the source, it looks like you should be able to access the data you're looking for using either:

// this works because the class implements Iterator
foreach ($myobject as $row) {
    echo $row['keys(n)']; // outputs "character"
}

or:

// this works because the class implements ArrayAccess
// don't ask me why they put keys and values in different arrays ('columns' and 'raw')
echo $myobject[0]['keys(n)']; // outputs "character"