Подскажите, как получить аналог кода из js в php? Ниже сам код js и его попытка трансляции в php, пожалуйста, ругайте сильнее, интересно, как сделать правильно . Спасибо! js: Код (Javascript): var arrCats = [ { name: 'Tishka', order: 0, eyesColor: 'red' }, { name: 'Koshka', order: 1, eyesColor: 'green' } ]; var greenEyesCat = arrCats.filter(function (cat) { return cat.eyesColor === 'green'; }).map(function (cat) { return cat.name + ' с зелеными глазами'; }); console.log(greenEyesCat); Cats.php: PHP: namespace App; class Cats { public static $color = 'yellow'; } Index.php: PHP: use App\Cats; class Cat extends Cats { public $name, $eyes; public function __construct($name, $eyes) { $this->name = $name; $this->eyes = $eyes; } public function getCatName() { return $this->name; } public function getCatEyes() { return $this->eyes; } public static function isCatWithColoredEyes($cat) { return $cat->eyes === parent::$color; // return $cat->eyes === 'green'; } public static function getCatsWhithColoredEyes($arrCats) { return array_filter($arrCats, 'self::isCatWithColoredEyes'); } public static function getCatNameWhithColoredEyes($cat) { return $cat->name; } public static function getCatsNamesWhithColoredEyes($arrColoredEyesCats) { return array_map('self::getCatNameWhithColoredEyes', $arrColoredEyesCats); } } Cats::$color = (isset($_GET['color']) && !empty($_GET['color'])) ? $_GET['color'] : 'red'; //Cats::$color = 'green'; $arrCats = [ new Cat('Тишка', 'red'), new Cat('Кошка', 'green'), new Cat('Пышка', 'green'), ]; var_dump(Cat::getCatsNamesWhithColoredEyes(Cat::getCatsWhithColoredEyes($arrCats)));
PHP: <?php $arrCats = [ [ 'name' => 'Tishka', 'order' => 0, 'eyesColor' => 'red' ], [ 'name' => 'Koshka', 'order' => 1, 'eyesColor' => 'green' ] ]; function greenEyesCat($arrCats){ foreach($arrCats as $item){ if($item['eyesColor'] == 'green'){ return $item['name'].' с зелеными глазами'; break; } } } echo greenEyesCat($arrCats); ?>
Спасибо! В js построена цепочка в точечной нотации, возможна ли реализация в php через текучий интерфейс?
Не уверен, что понял, о чём речь, но если ты про обращение к свойствам и методам объектов через точку в JavaScript, то в PHP для этого используется "стрелка" -> PHP: echo $object->property; $res = $object->method(); Чтобы можно было цепочки вызовов составлять - метод должен возвращать ссылку на объект своего класса PHP: Class Test { public function methodOne() { echo 'One'; return $this; } public function methodTwo() { echo 'Two'; return $this; } } $test = new Test(); $test->methodOne()->methodTwo();