【问题标题】:PHP intersection between array and object数组和对象之间的PHP交集
【发布时间】:2010-04-08 00:28:31
【问题描述】:

我有一个对象,假设它是这样的:

class Foo {
    var $b, $a, $r;

    function __construct($B, $A, $R) {
        $this->b = $B;
        $this->a = $A;
        $this->r = $R;
    }
}

$f = new Foo(1, 2, 3);

我想获取这个对象属性的任意切片作为数组。

$desiredProperties = array('b', 'r');

$output = magicHere($foo, $desiredProperties);

print_r($output);

// array(
//   "b" => 1,
//   "r" => 3
// )

【问题讨论】:

    标签: php arrays object intersection


    【解决方案1】:

    假设属性是公开的,这应该可以工作:

    $desiredProperties = array('b', 'r');
    $output = props($foo, $desiredProperties);
    
    function props($obj, $props) {
      $ret = array();
      foreach ($props as $prop) {
        $ret[$prop] = $obj->$prop;
      }
      return $ret;
    }
    

    注意: var 在这个意义上可能已被弃用。这是PHP4。 PHP5的方式是:

    class Foo {
      public $b, $a, $r;
    
      function __construct($B, $A, $R) {
        $this->b = $B;
        $this->a = $A;
        $this->r = $R;
      }
    }
    

    【讨论】:

      【解决方案2】:

      ...写到一半就想到了怎么做...

      function magicHere ($obj, $keys) {
          return array_intersect_key(get_object_vars($obj), array_flip($keys));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-19
        • 2017-11-15
        • 2012-12-21
        • 1970-01-01
        • 2023-01-17
        相关资源
        最近更新 更多