2017-09-15 63 views
-1

我想重新命名一些數組鍵,我把它們放到一個數組中,這些數組已經被preg_match_all匹配來組織數據。如何重命名由preg_match_all命令的數組鍵?

我有以下幾點:

$array = [ 
    '1. first paragraph goes here', 
    '<img src="http://www.xxs.com/image2asdasd.jpg">', 
    '2. second paragraph is also here', 
    '3. third paragraph is much longer then the rest', 
    '<img src="http://www.xxs.com/image2asdasd.jpg">' 
]; 

foreach($array as $string){ 
    if(preg_match_all("/(?:\d)\. (.*)/", $string, $output_array)) { 
     foreach($output_array[0] as $instructions_output){ 
      $info[] = $instructions_output; 
     } 
    } 
    if(preg_match_all("/<*img[^>]*src *= *[\"\']?([^\"\']*)/", $string, $cought_array)) { 
     $info[] = $cought_array[1][0]; 
    } 
} 

如果我print_r($info)我得到如下:

Array 
(
    [0] => 1. first paragraph goes here 
    [1] => http://www.xxs.com/image2asdasd.jpg 
    [2] => 2. second paragraph is also here 
    [3] => 3. third paragraph is much longer then the rest 
    [4] => http://www.xxs.com/image2asdasd.jpg 
) 

因爲他們被命令的preg_match,我想做以下

Array 
(
    [text] => 1. first paragraph goes here 
    [image] => http://www.xxs.com/image2asdasd.jpg 
    [text] => 2. second paragraph is also here 
    [text] => 3. third paragraph is much longer then the rest 
    [image] => http://www.xxs.com/image2asdasd.jpg 
) 

我試了一下:

我試圖重新命名它裏面,我將它設置爲$info['text'][]$info['image'][],但只有將其劃分像我下面展示。

Array 
(
    [text] => Array 
     (
      [0] => 1. first paragraph goes here 
      [1] => 2. second paragraph is also here 
      [2] => 3. third paragraph is much longer then the rest 
     ) 

    [image] => Array 
     (
      [0] => http://www.xxs.com/image2asdasd.jpg 
      [1] => http://www.xxs.com/image2asdasd.jpg 
     ) 
) 

回答

0

要使用字符串鍵替換數組元素的索引,第一,得到你想要替換爲字符串鍵的數組元素的初始值。然後,刪除數組元素。最後,用鍵添加一個新的元素到數組中。 注意:在PHP中,不能有兩個或更多個元素具有相同的密鑰。
實施例:

<?php 

$value_backup = $array[0]; 
unset($array[0]); 
$array['text'] = $value_backup; 

?> 
+0

哦,對了,我忘了我們不能有兩個同名的鍵。謝謝。 – Craig

+0

我很高興我幫助!如果我的答案幫助了你,請將我的答案設置爲正確的答案 – WhatsYourIdea

1
Array 
(
    [text] => 1. first paragraph goes here 
    [image] => http://www.xxs.com/image2asdasd.jpg 
    [text] => 2. second paragraph is also here 
    [text] => 3. third paragraph is much longer then the rest 
    [image] => http://www.xxs.com/image2asdasd.jpg 
) 

這不是一個數組。如果有3個文本和2個圖像索引,如何訪問它?

+0

是的,我忘記了關鍵名稱不能相同。 – Craig