Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort and Group Array

Status
Not open for further replies.

jesusatan123456

Programmer
Feb 16, 2006
3
CZ
Hello everybody,
i have some problems with arrays. Pls look at this ....

$arrToGroup = array('5 beers|January', '6 pepsi|January', '1 bred|February', '2 bananas');

i want output

Array
(
[0] => Array
(
[month] => January
[0] => 5 beers
[1] => 6 pepsi
)

[1] => Array
(
[month] => February
[0] => 1 bred
)
[2] => Array
(
[month] =>
[0] => 2 bananas
)
)



thnx for your help ...

Jesus
 
construct your array like this
Code:
$arrToGroup[] = array("month"=>"January",'5 beers', '6 pepsi);
$arrToGroup[] array("month"=>"February", '1 bred');
$arrToGroup[] = array("month"=>"",'2 bananas');

if you cannot change your constructor code

Code:
<?
$arrToGroup = array('5 beers|January', '6 pepsi|January', '1 bred|February', '2 bananas');
$newarray = array();
foreach ($arrToGroup as $val):
	$vals = array();
	if (!strpos($val, "|")): //test for a pipe
		$newarray[] = array("month"=>"", $val);
	else:
		$vals = explode("|",$val);
		$newarray[] = array("month"=>$vals[1], $vals[0]);
	endif;
endforeach;
echo "<pre>";
print_r($newarray);
echo "</pre>";
?>
 
sorry:

Code:
<?
$arrToGroup = array('5 beers|January', '6 pepsi|January', '1 bred|February', '2 bananas');
$newarray = array();
foreach ($arrToGroup as $val):
    $vals = array();
    if (!strpos($val, "|")): //test for a pipe
        $newarray["blankmonth"][] = $val;
    else:
        $vals = explode("|",$val);
        $newarray[$vals[1]][] = $vals[0];
    endif;
endforeach;

foreach ($newarray as $month=>$val):
	$month = $month=="blankmonth"?"":$month;
	$final[] = array_merge(array("month"=>$month), $val);
endforeach;
echo "<pre>";
print_r($final);
echo "</pre>";
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top