我一直试图将foreach与2个数组一起使用数小时。 这是我的代码:
function displayTXTList($fileName) {
if (file_exists($fileName)) {
$contents = file($fileName);
$string = implode($contents);
preg_match_all('#\[\[(\w+)\]\]#u', $string, $name);
preg_match_all('/style=(\'|\")([ -0-9a-zA-Z:]*[ 0-9a-zA-Z;]*)*(\'|\")/', $string, $name2);
$i = 0;
foreach ($name[1] as $index => $value) {
echo '<br/>' . $value, $name2[$index];
}
}
}
displayTXTList('smiley2.txt');
这是我得到的:
sadArray
cryingArray
sunArray
cloudArray
raining
coffee
cute_happy
snowman
sparkle
heart
lightning
sorry
so_sorry
etc...
但我想要这个:
sadstyle='background-position: -0px -0px;'
cryingstyle='background-position: -16px -0px;'
sunstyle='background-position: -32px -0px;'
etc...
实际的txt文件是:
[[sad]]<span class='smiley' style='background-position: -0px -0px;'></span>
[[crying]]<span class='smiley' style='background-position: -16px -0px;'></span>
[[sun]]<span class='smiley' style='background-position: -32px -0px;'></span>
[[cloud]]<span class='smiley' style='background-position: -48px -0px;'></span>
[[raining]]<span class='smiley' style='background-position: -64px -0px;'></span>
etc...
我怎么能这样做?我是新来的,所以请不要注意:/
答案 0 :(得分:2)
您正在输出数组作为字符串(因此输出中为Array
,如果将数组转换为字符串(例如,使用echo
),PHP会将其转换为"Array"
)。而是访问数组中的匹配(我假设$name2
的组0,请检查):
echo '<br/>' .$value , $name2[0][$index];
^^^--- was missing
function displayTXTList($fileName) {
if (!file_exists($fileName)) {
return;
}
$string = file_get_contents($fileName);
$names = preg_match_all('#\[\[(\w+)\]\]#u', $string, $matches) ? $matches[1] : array();
$styles = preg_match_all(
'/style=(\'|\")([ -0-9a-zA-Z:]*[ 0-9a-zA-Z;]*)*(\'|\")/', $string, $matches
) ? $matches[0] : array();
foreach ($names as $index => $name) {
$style = $styles[$index];
echo '<br/>', $name, $style;
}
}
displayTXTList('smiley2.txt');