如何在php中的对象数组中搜索属性?

时间:2017-05-08 10:56:55

标签: php arrays

我有一个如下所示的数组  如果我在php中提供slab id值,是否有可能找到数组的键索引?

Array
       (
           [0] => incentiveSlab Object
               (
                   [slabId] => 1
                   [templateId] => 1
                   [startPoint] => 0
                   [endPoint] => 1000000
                   [value] => 0
               )

           [1] => incentiveSlab Object
               (
                   [slabId] => 2
                   [templateId] => 1
                   [startPoint] => 1000000
                   [endPoint] => 2500000
                   [value] => 0.5
               )


       )

2 个答案:

答案 0 :(得分:3)

类似的东西:

function getIndex($array, $slabId) {
    foreach($array as $index => $item) {
        if($item->slabId == $slabId)
            return $index;
    }
}

答案 1 :(得分:0)

  

我建议,更改您的数据结构

  • 使用slabId作为Array_Index
  • 例如

    阵列

       [0] => NULL
    
       [1] => incentiveSlab Object
           (
               [slabId] => 1
               [templateId] => 1
               [startPoint] => 0
               [endPoint] => 1000000
               [value] => 0
           )
    
       [2] => incentiveSlab Object
           (
               [slabId] => 2
               [templateId] => 1
               [startPoint] => 1000000
               [endPoint] => 2500000
               [value] => 0.5
           )
    

  

或者如果你在slabId中有太多的变化,请使用关联数组