Answer the question
In order to leave comments, you need to log in
How to refer to the property of an object without knowing this property?
How to refer to item by template
foreach ($model as $item){
for ($i = 0; $i <= count($pattern); $i++){
//должно выглядеть вот так $item->catalog->name и тд.
$data[] = $item->$pattern[$i];
}
}
writeFromModel($model, [
"catalog->name",
"catalog->article"
]);
Answer the question
In order to leave comments, you need to log in
The semantics of the task is very bad (catalog in the catalog, does the catalog have a product? One? :)
But in general, on the knee, how to get the nested depth values
<?php
$catalog = new stdClass();
$catalog->product = new stdClass();
$catalog->product->item = 'Short';
$catalog->product->model = 'Adidas';
$catalogPaths = ['product.item', 'product.model'];
function extractValuesByPath(object $obj, array $paths) {
return array_reduce($paths, function(array $values, string $pattern) use($obj) {
$values[] = extractPathValue($obj, $pattern);
return $values;
}, []);
}
function extractPathValue($obj, $pattern) {
$paths = explode('.', $pattern);
foreach($paths as $path) {
if (!property_exists($obj, $path)) {
// Можно нулл вернуть или к пример `undefined $path`
throw new InvalidArgumentException('Нет такого свойства во входящих данных!');
}
$obj = $obj->$path;
}
return $obj;
}
$res = extractValuesByPath($catalog, $catalogPaths);
var_dump($res);
// [
// 'Short',
// 'Adidas',
// ]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question