arrays - How to get value from object in php
Get the solution ↓↓↓I need to get the value of[text]
from all these object - class.
I can get values from arrays But from these class object thing in array ,I am unable to get the values of[text]
.
Any help would be greatly appreciated.
Array
(
[0] => stdClass Object
(
[text] => time
[tr] => Array
(
[0] => stdClass Object
(
[text] => while
[syn] => Array
(
[0] => stdClass Object
(
[text] => when
)
)
)
[1] => stdClass Object
(
[text] => occasion
[syn] => Array
(
[0] => stdClass Object
(
[text] => moment
)
[1] => stdClass Object
(
[text] => day
)
[2] => stdClass Object
(
[text] => date
)
)
)
)
)
)
Answer
Solution:
It's not the most elegant solution but something like this should do the trick:
<?php
$data = [
[
'text' => 'time',
'tr' => [
'text' => 'while',
'syn' => [
'text' => 'when'
],
[
'text' => 'occasion',
'syn' => [
[
'text' => 'moment'
],
[
'text' => 'day'
],
[
'text' => 'date'
]
]
]
]
]
];
$data = json_decode(json_encode($data));
function recurseProperties($object) {
$text = [];
foreach ($object as $property => $value) {
if ($property === 'text') {
echo $property . ' => ' . $value . "\n";
$text[] = $value;
} else {
$text = array_merge($text, recurseProperties($value));
}
}
return $text;
}
function extractText($data) {
$text = [];
foreach ($data as $object) {
$text = array_merge($text, recurseProperties($object));
}
return $text;
}
var_dump(extractText($data));
Alternatively if you are comfortable working with arrays and it is a json source, you can just do:
json_decode($jsonString, true)
Which will convert it to an associative array see: https://www.php.net/manual/en/function.json-decode.php
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: composer detected issues in your platform: your composer dependencies require a php version ">= 8.0.2".
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.