Well guys i've been struggling with this for about 5 hours now and i realise my brain is fried thought i better get some people who know what they are doing :p Now i just have to explain the problem properly.
I want to display all the goal scorers with just their name and goal time for each separate goal after it like: Carlton Dickson (23, 53) Danniel Tasker (1).
The only way i could think to do this is replace the array with a new one which has in it all the goals in element. So making one row for the names and one row with all the goals in them. Maybe i am not looking at this the right way?
Cheers dudes.
array(8) {
[0]=> array(3) {
["fname"]=>
string(7) "Carlton"
["sname"]=>
string(7) "Dickson"
["time"]=>
string(2) "23"
}
[1]=> array(3) {
["fname"]=>
string(7) "Carlton"
["sname"]=>
string(7) "Dickson"
["time"]=>
string(2) "53"
}
[2]=> array(3) {
["fname"]=>
string(6) "Daniel"
["sname"]=>
开发者_高级运维 string(6) "Tasker"
["time"]=>
string(1) "1"
}
You could rebuild your array this way:
$newArray = array();
foreach($array as $player) {
$name = $player['fname'] . " " . $player["sname"];
if(!array_key_exists($name, $newArray)) {
$newArray[$name] = array();
}
$newArray[$name][] = $player['time'];
}
The resulting array will be:
Array
(
[Carlton Dickson] => Array
(
[0] => 23
[1] => 53
)
[Daniel Tasker] => Array
(
[0] => 1
)
)
i.e. the key is the name, and the value is an array of the goals. Of course you can also concatenate the goals as a string, it depends on what else you want to do with the data.
Then printing is just a matter of traversing the array:
foreach($newArray as $player => $goals) {
echo $player . " (" . implode(',', $goals) . ") <br />"; // or PHP_EOL
}
$scorers = array();
foreach ($goals as $goal) {
$name = "{$goal['fname']} {$goal['sname']}";
$scorers[$name] = isset($scorers[$name]) ? "{$scorers[$name]}, {$goal['time']}" : $goal['time'];
}
foreach ($scorers as $scorer => $goals) {
echo "$scorer ($goals)";
}
Assuming you have a $goals
array like so:
$goals = array(
array('fname' => 'Carlton', 'sname' => 'Dickson', 'time' => '23'),
array('fname' => 'Carlton', 'sname' => 'Dickson', 'time' => '53'),
array('fname' => 'Daniel', 'sname' => 'Tasker', 'time' => '1')
);
精彩评论