如果给定字符串值作为 Codeigniter 中的变量,如何从数组中获取键值

How to get the key value from an array if given string value as a variable in Codeigniter

我不确定问这个问题是否有意义,但我有一个模型:

function update_profile_image($id, $image, $data){
    $data1=array('profile_thumb'=> $data['images_urls'][$index]);
    $this->db->where('property_ref_id',$id);
    $this->db->update('vbc_property_images',$data1);
}

这里$data是一个数组:

Array
(
[images_urls] => Array
    (
        [0] => property_image_11.png
        [1] => property_image_13.png
        [2] => property_image_14.png
    )

)

模型中的$image是这个数组中任意一张图片的名字,例如'property_image_13.png'.

我正在尝试做一些事情,我可以通过 $image 获取像 $index([0], [1]..) 这样的键值,这样在我的查询中它会自动检测选择了哪个图像。

请帮忙。

如果我对你的问题理解正确,你想搜索 $data 中定义的值 $image,以及 return 匹配元素的键。如果是这样,array_search 就是您所需要的。

$key = array_search($image, $data);

联机帮助页的描述:

Searches the array for a given value and returns the corresponding key if successful

可以在数组上循环获取图片的key

foreach($data['images_urls'] as $key => $value) {
   if($value == $image) {
       $index = $key;
       break;
   }
}

另一种解决方案是使用 array_search()

$index = array_search($image, $data['images_urls']);