2010-02-21 114 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的對象。