如果在 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]..) 这样的键值,以便在我的查询中它会自动检测选择了哪个图像。

请帮忙。

您可以循环数组以获取图像的键

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

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

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

正确理解了您的问题,您想$data搜索 $image 中定义的值,并返回匹配元素的键。如果是这样,array_search就是您所需要的。

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

来自手册页的说明:

在数组中搜索给定值,如果成功,则返回相应的键