【问题标题】:creating array of objects from array of arrays, using static method call (PHP)使用静态方法调用(PHP)从数组数组创建对象数组
【发布时间】:2014-10-08 23:47:13
【问题描述】:

我有一个这样的数组:

// Define pages
$pages = array(
    "home" => array(
        "title" => "Home page",
        "icon" => "home"
    ),
    "compositions" => array(
        "title" => "Composition page",
        "icon" => "music"
    ),
);

而我想要完成的是,拥有:

$navigation = Utils::makeNavigation($pages);

,创建$navigation作为对象数组,这样我可以在我的视图中解析它 像这样:

foreach($navigation as $nav_item){
    echo $nav_item->page; // home(1st iter.), compositions(2nd iter.)
    echo $nav_item->title;// Home page, Composition page
    echo $nav_item->icon; // home, music
}

staticUtil-like-class 方法对这类问题有用吗?

编辑

我想出了这样的东西,这看起来可以吗?

<?php
class Utils {

    protected static $_navigation;

    public static function makeNavigation($pages = array()){

        if (!empty($pages)){
            foreach ($pages as $page => $parts) {
                $item = new stdClass;
                $item->page = $page;

                foreach ($parts as $key => $value) {
                    $item->$key = $value;
                }
                self::$_navigation[] = $item;
            }
        return self::$_navigation;
        }
    }
}

【问题讨论】:

  • 你区分“好”和“坏”的标准是什么?
  • @zerkms 请看我的编辑..
  • 什么是“好”?可以客观衡量吗?对一个人来说“ok”,对另一个人来说是“not ok”。这对我来说“不好”——我会改用array_map。这算作答案吗?
  • 你能举一个关于我的情况的小例子吗,你会如何使用array_map
  • 我会用它来代替循环

标签: php class static


【解决方案1】:

假设您在代码中手动创建数组,只需转换为对象:

$pages = array(
    "home" => ( object ) array(
        "title" => "Home page",
        "icon" => "home"
    ),
    "compositions" => ( object ) array(
        "title" => "Composition page",
        "icon" => "music"
    ),
);

这将允许像对象一样访问它们:

$pages->home->title;

或者像这样循环遍历它们:

for ( $pages as $pageName => $pageObject ) echo $pageName . " has title: " . $pageObject->title;

【讨论】:

    【解决方案2】:

    我会将创建作为类的静态成员包含在内,以将特定于类的代码保持在一起:

    class NavItem
    {
    //  Static member does not require an object to be called
    static function create ($def)
    {
        $ret = array ();
        foreach ($def as $idx=>$navDef)
            $ret [$idx] = new NavItem ($navDef);
        return $ret;
    }
    function __construct ($def)
    {
        // Do something more specific with the current def (title, icon array)
        $this->param = $def;
    }
    
    function display ()
    {
        //  Simple example
        echo $this->param ['title'];
        echo $this->param ['icon'];
    }
        var                     $param;
    };
    
    //  Using your pages array as above
    $pages = NavItem::create ($pages);
    foreach ($pages as $idx=>$page)
        $page->display ();
    

    【讨论】:

    • 这不是我想要完成的,我举了一个例子来说明我想得到什么。在一个 itterable 对象中拥有所有 3 个属性。你错过了我也需要的page 属性。
    猜你喜欢
    • 2012-07-16
    • 2023-03-29
    • 2019-11-02
    • 2012-07-06
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2020-05-24
    相关资源
    最近更新 更多