检查多维数组中的索引是否为数组

时间:2012-08-04 20:06:02

标签: php arrays multidimensional-array header

代码:

    $row['text'] = 'http://t.co/iBSiZZD4 and http://t.co/1rG3oNmc and http://t.co/HGFjwqHI and http://t.co/8UldEAVt';

    if(preg_match_all('|http:\/\/t.co\/.{1,8}|i',$row['text'],$matches)){
        foreach($matches[0] as $value){
            $headers = get_headers($value,1);
            if(is_array($headers['Location'])){
                $headers['Location'] = $headers['Location'][0];
            }
            $row['text'] = preg_replace('|http:\/\/t.co\/.{1,8}|i', '<a href="' . $headers['Location'] . '">' . $headers['Location'] . '</a>',$row['text']);
        }
    }

这与get_headers()有关。有时get_headers($url,1)返回一个带有位置索引键的数组,如下所示:[Location]=>Array([0]=>url1 [1]=>url2)。如果[Location]存在,我基本上希望[Location][0]等于[Location][0]。但是,上面的代码似乎没有完成该任务。我也尝试了array_key_exists()isset(),但都没有解决问题。想法?

1 个答案:

答案 0 :(得分:2)

不要试图动态更换。首先获取所有值,然后在一个批处理中进行替换(使用两个数组作为$search$replace参数)。

<?php

    $replace = array();
    $row = array('text' => 'http://t.co/iBSiZZD4 and http://t.co/1rG3oNmc and http://t.co/HGFjwqHI and http://t.co/8UldEAVt');
    if (preg_match_all('|http:\/\/t.co\/.{1,8}|i', $row['text'], $search)) {
        foreach ($search[0] as $value) {
            $headers = get_headers($value, 1);
            if (is_array($headers['Location'])) {
                $headers['Location'] = $headers['Location'][0];
            }
            $replace[] = "<a href='{$headers["Location"]}'>{$headers["Location"]}</a>";
        }
        $row['text'] = str_replace($search[0], $replace, $row['text']);
        echo $row["text"];
    }

P.S。 - 下次,请告诉我们您的问题的背景,告诉我们您“正在提供解决缩短的网址的服务”,不要让我从您的代码中解决这个问题。