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


Checking if an index in a multidimensional array is an array

代码:

    $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][0]存在,我基本上想使[Location]等于[Location][0]。然而,上面的代码似乎并不能完成这项任务。我也尝试过array_key_exists()isset(),但都没有解决问题。想法?

不要试图动态替换。首先获取所有值,然后在一批中进行替换(使用两个数组作为$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"];
    }

第页。S.-下次,请告诉我们你的问题的上下文,告诉我们你"正在制作一个解决缩短URL的服务",不要让我从你的代码中单独弄清楚。