Can I use an instantiated Object as an Array Key?

前端 未结 6 1293
执笔经年
执笔经年 2020-12-15 15:47

For example:

$product = new Product(\"cat\");

if(isset($sales[$product])){
     $sales[$product]++;
}
else{
     $sales[$product] = 1;
}
6条回答
  •  攒了一身酷
    2020-12-15 16:03

    You could have two arrays:

    Array 1 contains the keys:   |  Array 2 contains the values
    +--------+-------------+     |  +--------+------------+
    | index: | value:      |     |  | index: | value:     |
    | 0      | Object(key) |     |  | 0      | sth(value) |
    | 1      | Object(key) |     |  | 1      | sth(value) |
    +--------+-------------+     |  +--------+------------+
    

    You search for the Object in array 1,
    then you pick the index of that Object
    use it as index for array 2 and
    => get the value

    in php code

    public function getValue($ObjectIndexOfYourArray){
      foreach(array1 as $key => $value) {
        if($value == ObjectIndexOfYourArray){
          return array2[$key];
        }
      }
    }
    

    I hope it helps

提交回复
热议问题