A
A
Alexander2021-04-02 13:08:57
PHP
Alexander, 2021-04-02 13:08:57

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];
            }
        }


this is what is being sent
writeFromModel($model, [
            "catalog->name",
            "catalog->article"
        ]);


and in name there must be an array of name, arcticel

in such an implementation gives an error "Array to string conversion"
is it possible to implement this in php? And How?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maksim Fedorov, 2021-04-02
@Maksclub

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 question

Ask a Question

731 491 924 answers to any question