2012-08-04 83 views
1

的代碼:檢查如果在多維數組的索引是陣列

$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(),但都沒有解決問題。思考?

+0

你確定'$ headers ['Location']'是一個數組嗎? – SomeKittens 2012-08-04 20:07:45

+0

'$ headers ['Location']'通常不是一個數組。這就是爲什麼我要檢查它是否是一個數組,以便我可以採取替代措施。 – Chad 2012-08-04 20:11:37

+0

這應該工作...確保$標頭不是隻讀的。 – Aadaam 2012-08-04 20:13:25

回答

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. - 下一次,請告訴我們您問題的背景,告訴我們您「正在提供解決縮短網址的服務」,請不要讓我從您的代碼中單獨弄清楚。

+0

在附註中,我想我可能需要找到get_headers()的替代方案。它始終無法打開流,可能是因爲我擁有的鏈接數量。 – Chad 2012-08-04 21:13:26