2010-02-21 90 views
1

这里是我的var_dump:选择获取基于ID的名称

array(2) { 
    [1]=> 
    object(stdClass)#382 (3) { 
    ["name"]=> 
    string(12) "Other fields" 
    ["sortorder"]=> 
    string(1) "1" 
    ["id"]=> 
    int(1) 
    } 
    [3]=> 
    object(stdClass)#381 (3) { 
    ["name"]=> 
    string(6) "custom" 
    ["sortorder"]=> 
    string(1) "2" 
    ["id"]=> 
    int(3) 
    } 
} 

我需要一些PHP来选择第二个对象,显然它不会永远是第二个对象,所以我需要根据选择它在它的[“名字”]上,这将永远是“习惯”。

下面的代码给我所有的名字,但我只想“自定义”,并获得自定义的ID。

foreach ($profilecats as $cat) { 
    $settings .= $something->name; 
} 

回答

1
foreach ($profilecats as $cat) { 
    if ($cat->name == 'custom') { 
    echo $cat->id; 
    } 
} 
0

....

foreach ($profilecats as $value) 
{ 
    if ($value === "custom") 
    { 
    $id = $profilecats['id']; 
    break; 
    } 
} 
0
function get_object($array, $name) 
{ 
    foreach ($array as $obj) 
    { 
     if ($obj->name == $name) 
     { 
      return $obj; 
     } 
    } 
    return null; 
} 
1

备选:

class ObjectFilter extends FilterIterator 
{ 
    protected $propName = null; 
    protected $propValue = null; 

    public function filterBy($prop, $value) 
    { 
     $this->propName = $prop; 
     $this->propValue = $value; 
    } 

    public function accept() { 
     if(property_exists($this->current(), $this->propName)) { 
      return $this->current()->{$this->propName} === $this->propValue; 
     } 
    } 
} 

$finder = new ObjectFilter(new ArrayIterator($cats)); 
$finder->filterBy('name', 'custom'); 
foreach($finder as $cat) { 
    var_dump($cat); 
} 

这是一个通用滤波器,通过属性和属性值的过滤器。只需更改filterBy的参数,例如filterBy('id', 1)只会返回属性id设置为1的对象。