Reputation: 6167
I would want to abstract a value of a property in the below array. May I know how can I do with php?
print_r($array);
Array
(
[0] => {property1: 'value12', property2: 'value12', property3: 'value13'}
[1] => {property1: 'value21', property2: 'value22', property3: 'value23'}
)
May I know how to read the value of attribute property1 of each array?
Upvotes: 0
Views: 109
Reputation: 22480
If you have an array with objects this might be the way to go:
$myArrayWithObjects = [
0 => (Object) ['property1' => 'value12', 'property2' => 'value12', 'property3' => 'value13'],
1 => (Object) ['property1' => 'value21', 'property2' => 'value22', 'property3' => 'value23']
];
echo 'Array with Objects: ' . $myArrayWithObjects[1]->property3 . "\n";
// prints: Array with Objects: value23
you can loop over the "first array" and use the object
like so:
foreach($myArrayWithObjects as $myObject) {
echo 'Array with Objects foreach: ' . $myObject->property2 . "\n";
}
if it is an array with arrays go this way:
$myArray = [
0 => ['property1' => 'value12', 'property2' => 'value12', 'property3' => 'value13'],
1 => ['property1' => 'value21', 'property2' => 'value22', 'property3' => 'value23']
];
echo 'Array with arrays: ' . $myArray[1]['property3'] . "\n";
// prints: Array with arrays: value23
and the foreach loop for array with arrays accordingly:
foreach($myArray as $innerArray) {
echo 'Array with arrays foreach: ' . $innerArray['property2'] . "\n";
}
you can play with it online here: http://sandbox.onlinephpfunctions.com/code/7b8f5740350278f811ab9f998b9501c154697abf
Upvotes: 2