代码之家  ›  专栏  ›  技术社区  ›  Stark

如何重命名由preg\u match\u all排序的数组键?

  •  -1
  • Stark  · 技术社区  · 7 年前

    我试图重命名我放入数组中的一些数组键,该数组已由preg\u match\u 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
            )
    )
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   loadinger    7 年前
    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个图像索引,如何访问它?

        2
  •  0
  •   WhatsYourIdea    7 年前

    要用字符串键替换数组元素的索引,首先,获取要替换为字符串键的数组元素的原始值。然后,删除数组元素。最后,用键向数组中添加新元素。
    例子:

    <?php
    
    $value_backup = $array[0];
    unset($array[0]);
    $array['text'] = $value_backup;
    
    ?>