这是一个选项。
您的初始数组(这可能是从数据库中获取的。我有点根据您的问题猜测确切的结构,但应该很接近):
/* Initial array
Array
(
[option] => Array
(
[0] => Array
(
[name] => Roses
[value] => red
)
[1] => Array
(
[name] => Violets
[value] => blue
)
[ ... ]
)
)
*/
循环遍历它并使其成为一个数组,每个值都包含一个颜色数组。基本上将$value
s 分组在他们的$name
. 这也很方便,因为您的数据库条目是否乱序也没关系。
// Loop all $product['option']
foreach ($product['option'] as $option) {
// If we don't have an array made for this $name, make one
if (!is_array( $products[ $option['name'] ] ) )
$products[ $option['name'] ] = array();
// Add the $value to the $name's array
$products[ $option['name'] ][] = $option['value'];
}
/* $products =
Array
(
[Roses] => Array
(
[0] => red
[1] => blue
[2] => white
)
[Violets] => Array
(
[0] => blue
[1] => white
)
)
*/
接下来只是句子结构的问题,将它们组合在一起。由于您有一个方便的数组,您还可以快速执行多种其他形式的输出 - 这仅适用于您的句子问题。
// Loop the new array of name=>array(vals)
foreach($products as $name => $value){
// Counter variables and initial values for output
$cnt = count($value);
$cur = 2;
$out = $name . " are ";
// Loop all $values for the current $name
foreach($value as $v){
// Make the output
$sep = ($cur > $cnt ? "."
: ($cnt == 2 || $cur == $cnt ? " and " : ", ") );
$out .= $v . $sep;
$cur++;
}
// Save the output to the name array
$products[$name]["out"] = $out;
}
现在可以在可以访问$products
数组的任何地方使用此输出
echo $products["Roses"]["out"];
echo $products["Violets"]["out"];
/*
Output:
Roses are red, blue and white.
Violets are blue and white.
*/
http://codepad.org/sL8YhzCq