我有以下数组...
[0] => Array
(
[Name] => Steve Richard
[Car_Colour] => Red
)
[1] => Array
(
[Name] => Scott Lucas
[Car_Colour] => Orange
)
[2] => Array
(
[Name] => Danny Sisum
[Car_Colour] => Red
)
[3] => Array
(
[Name] => Alice Small
[Car_Colour] => Green
)
如何输出数组中的数据,但是按车辆颜色对数据进行分组,那么拥有两辆红色汽车的人会出现在红色标题下面,其他人是橙色还是绿色?
示例:
People with **Red** cars
Name:** Steve Richard
Car Colour:** Red
Name:** Danny Sisum
Car Colour: Red
People with **Orange** cars
Name:** Scott Lucas
Car Colour:** Orange
People with **Green** cars
Name:** Alice Small
Car Colour:** Green
答案 0 :(得分:2)
你可以尝试
$array = array(
"0" => Array("Name" => "Steve Richard","Car_Colour" => "Red"),
"1" => Array("Name" => "Scott Lucas","Car_Colour" => "Orange"),
"2" => Array("Name" => "Danny Sisum","Car_Colour" => "Red"),
"3" => Array("Name" => "Alice Small","Car_Colour" => "Green"));
$list = array();
foreach($array as $data)
{
$list[$data['Car_Colour']][] = $data;
}
var_dump($list);
如上所示显示
echo "<pre>";
foreach($list as $color => $data)
{
printf("People with **%s** cars\n",$color);
foreach($data as $info)
{
printf("\tName:** %s\n",$info['Name']);
printf("\t Car Colour:** %s\n",$info['Car_Colour']);
}
print(PHP_EOL);
}
输出
People with **Red** cars
Name:** Steve Richard
Car Colour:** Red
Name:** Danny Sisum
Car Colour:** Red
People with **Orange** cars
Name:** Scott Lucas
Car Colour:** Orange
People with **Green** cars
Name:** Alice Small
Car Colour:** Green
答案 1 :(得分:1)
$array = array(); // The array you currently have
// Grouping
$grouped = array();
foreach ($array as $item) {
$colour = $item['Car_Colour'];
if (!isset($grouped[$colour])) {
$grouped[$colour] = array();
}
$grouped[$colour][] = $item['Name'];
}
// Output
$output = '';
foreach ($grouped as $colour => $names) {
$output .= 'People with **' . $colour . '** cars' . "\n\n";
foreach ($names as $name) {
$output .= "\t" . 'Name:** ' . $name . "\n";
$output .= "\t" . 'Car Colour:** ' . $colour . "\n";
}
}
echo $output;
答案 2 :(得分:1)
类似的东西:
$grouped_array = array();
foreach($array as $person){
if(!isset($grouped_array[$person['car_colour'])){
$grouped_array[$person['car_colour']] = array();
}
$grouped_array[$person['car_colour'][] = $person['name'];
}
答案 3 :(得分:0)
$arr_color = array(); // This line is only truly neccessary if $arr_data can be empty
foreach ($arr_data as $arr)
$arr_color[$arr["Car_Colour"]][] = $arr["Name"];
// Display
foreach ($arr_color as $color => $lst_persons) {
echo "<p>People with *** $color *** cars</p>";
foreach ($lst_persons as $person) {
echo "Name: " . $person . "<br>";
}
}
输入:
$arr_data = array(
0 => array(
"Name" => "Steve Richard",
"Car_Colour" => "Red"
),
1 => array(
"Name" => "Scott Lucas",
"Car_Colour" => "Orange"
),
2 => array(
"Name" => "Danny Sisum",
"Car_Colour" => "Red"
),
3 => array(
"Name" => "Alice Small",
"Car_Colour" => "Green"
)
);
输出:
People with *** Red *** cars
Name: Steve Richard
Name: Danny Sisum
People with *** Orange *** cars
Name: Scott Lucas
People with *** Green *** cars
Name: Alice Small