开发者

Select from Array to get ID based on Name

Here is my var_dump:

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)
  }
}

I need some PHP to select the 2nd object, obviously it wont always be the 2nd object, so I need to select it based on its ["name"] which will always be "custom".

The below code give's me all the names but I just want "custom" and the get the ID of custom.

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


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


Alternative:

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);
}

This is a generic filter that filters by property and property value. Just change the arguments for filterBy, e.g. filterBy('id', 1) would only return objects with property id set to 1.


function get_object($array, $name)
{
    foreach ($array as $obj)
    {
        if ($obj->name == $name)
        {
            return $obj;
        }
    }
    return null;
}


....

foreach ($profilecats as $value)
{
  if ($value === "custom")
  {
    $id = $profilecats['id'];
    break;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜