1

大家好我有一个数组

$data = array("https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg",
          "https://lh4.googleusercontent.com/-F_ngXcmSdxY/UbBLypozWvI/AAAAAAAAAew/juDGaqNUiSc/w958-h715-no/411.jpg",
          "https://lh6.googleusercontent.com/-dxOkxkoZd0k/Ua3jQFu2WqI/AAAAAAAAAQc/eYX-u6mtF3k/w958-h715-no/113.jpg",
          "https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg");

如何使用子句从数组中获取特定数据?

例如。我想用 121.jpg 从数组中提取数据。

谢谢!

4

2 回答 2

2

您可以循环数组并检查值:

while (list($key, $value) = each ($data)) {
    if(strpos($value, '121.jpg') !== false)
    {
        var_dump($value);
    }   
}
于 2013-06-07T01:59:33.053 回答
1

可能是你的意思Closure?如果有多个具有相同名称的图像怎么办?

function get_image_url($name, array $images) {
    $image_url = array_filter($images, function($value) use ($name) {
        return (preg_replace('/^(.*\/)/', '', $value) == $name);
    });

    if (0 == sizeof($image_url)) {
        return false;
    } elseif (1 == sizeof($image_url)) {
        return reset($image_url);
    }

    return $image_url;
}

例子:

$images = array(
        "https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg",
        "https://lh4.googleusercontent.com/-F_ngXcmSdxY/UbBLypozWvI/AAAAAAAAAew/juDGaqNUiSc/w958-h715-no/411.jpg",
        "https://lh6.googleusercontent.com/-dxOkxkoZd0k/Ua3jQFu2WqI/AAAAAAAAAQc/eYX-u6mtF3k/w958-h715-no/113.jpg",
        "https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg",
        "121.jpg"
    );

    var_dump(get_image_url('111.jpg', $images));
    // string(103) "https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg"

    var_dump(get_image_url('121.jpg', $images));
    // array(2) {
    //  [3] =>
    //  string(103) "https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg"
    //  [4] =>
    //  string(7) "121.jpg"
    // }

    var_dump(get_image_url('invalid.jpg', $images)); 
    // bool(false)
于 2013-06-07T02:57:31.193 回答