Here's an option.
Your initial array (this is probably grabbed from a database. I'm kind of guessing the exact structure based on your question, but should be close):
/* Initial array
Array
(
[option] => Array
(
[0] => Array
(
[name] => Roses
[value] => red
)
[1] => Array
(
[name] => Violets
[value] => blue
)
[ ... ]
)
)
*/
Loop through it and make it into an array with each value holding an array of colors. Basically grouping $value
s on their $name
. This is pretty handy also because it doesn't matter if your database entries are out of order.
// 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
)
)
*/
Next it's just a matter of sentence structure, combining it all together. Since you have a handy array, you can also do a multitude of other forms of output quickly - this is just for your sentence question.
// 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;
}
This output can be used now anywhere you can access the $products
array
echo $products["Roses"]["out"];
echo $products["Violets"]["out"];
/*
Output:
Roses are red, blue and white.
Violets are blue and white.
*/
http://codepad.org/sL8YhzCq