我试图重命名一些数组密钥,我已将这些数组密钥放入已与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 :(得分:2)
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个图像索引,如何访问它?
答案 1 :(得分:0)
要使用字符串键替换数组元素的索引,首先,将要替换的数组元素的原始值获取为字符串键。然后,删除数组元素。最后,使用键向数组添加一个新元素。 注意:在PHP中,您不能拥有两个或多个具有相同键的元素。
例如:
<?php
$value_backup = $array[0];
unset($array[0]);
$array['text'] = $value_backup;
?>