在foreach循环中,我一直试图访问和操作数组中的某些名称值对,但没有成功。
我的数据在如下所示的数组中:
[0] => Array
(
[subject] => math
[price] => 5
[year] => 2006
)
[1] => Array
(
[subject] => reading
[price] => 7
[year] => 2007
[author] => Smith
[publisher] => Press
)
[2] => Array
(
[subject] => reading
[price] => 9
[year] => 2008
[author] => Jones
[copyright] => 1999
)我的代码是:
$count = count($array);
for ($i = 0; $i < $count; $i++) {
foreach($array[$i] as $name => $value) {
if(preg_match('(subject|price|year)', $name) != 1) {
@$desc .= '-'.$name.'-'.$value;
} else {
$desc = '';
}
echo $i.' : '.$desc.'<br />';
}
}我希望上面代码的输出是:
0 : subject-math / price-5 / year-2006
1 : subject-reading / price-7 / year-2007 / author-Smith-publisher-Press
2 : subject-reading / price-9 / year-2008 / author-Jones-copyright-1999我面临的主要问题是,我不知道如何组合和回显所有不符合preg_match条件的名称值对。本质上是主题,价格和年份,每个记录都是通用的,但我希望能够访问的任何其他记录都合并在一起作为一个项目。
提前感谢您的帮助!
发布于 2018-12-29 08:34:41
这段代码将执行您想要的操作。它循环遍历您的数组,将所有键-值对推入一个数组中,然后回显该数组的内爆(使用/)。subject、price和year的值都有自己的条目,而所有其他值都被推入一个数组中,然后使用-对该数组进行内爆,以提供所需的输出。不是使用preg_match来匹配关键字,而是使用简单的in_array:
foreach ($data as $k => $d) {
$out = array();
foreach ($d as $key => $value) {
if (in_array($key, ['subject', 'price', 'year'])) {
$out[] = "$key-$value";
}
else {
$out['others'][] = "$key-$value";
}
}
if (isset($out['others'])) $out[] = implode('-', $out['others']);
unset($out['others']);
echo "$k : " . implode(' / ', $out) . "\n";
}输出:
0 : subject-math / price-5 / year-2006
1 : subject-reading / price-7 / year-2007 / author-Smith-publisher-Press
2 : subject-reading / price-9 / year-2008 / author-Jones-copyright-1999发布于 2018-12-29 08:46:20
我想,这将是最简单的实现:
foreach ($array as $index => $item)
{
$result = array_filter
([
'subject-' . array_shift($item),
'price-' . array_shift($item),
'subject-' . array_shift($item),
implode('-', $item)
]);
$result = implode(' / ', $result);
echo "$index: $result\n";
}https://stackoverflow.com/questions/53965605
复制相似问题