12 Dec
function groupArrayOnIdStr($old_arr,$sortText){
$arr = array();
if(@is_array($old_arr)){
foreach($old_arr as $key => $item)
{
$arr[$item[$sortText]][$key] = $item;
}
}
@ksort($arr, SORT_NUMERIC);
return $arr;
}
For ewxample i have below Array
$mainArra = Array (
[0] => Array ( [id] => 4 [docDataName] => Food [title] => Allergy – Food [dataType] => Unstructured [profileId] => 126 [profileDob] => 1988-10-19 ) [1] => Array ( [id] => 4 [docDataName] => Food [title] => Allergy – Food [dataType] => Unstructured [profileId] => 53 [profileDob] => 1992-11-19 ) [2] => Array ( [id] => 3 [docDataName] => ALL [title] => Medication – ALL [dataType] => Unstructured [profileId] => 126 [profileDob] => 1988-10-19 ) [3] => Array ( [id] => 5 [docDataName] => Rotavirus [title] => Immunization – Rotavirus [dataType] => Structured_Unstructured [profileId] => 53 [profileDob] => 1992-11-19 ) [4] => Array ( [id] => 5 [docDataName] => DTaP/DT [title] => Immunization – DTaP/DT [dataType] => Structured_Unstructured [profileId] => 126 [profileDob] => 1988-10-19 ))
I want to group this array on key “profileId” values
So i will use
$resultArra = groupArrayOnIdStr($mainArra,’profileId’);
So in result i will got as follow:-
Array (
[53] => Array ( [1] => Array ( [id] => 4 [docDataName] => Food [title] => Allergy – Food [dataType] => Unstructured [profileId] => 53 [profileDob] => 1992-11-19 ) [3] => Array ( [id] => 5 [docDataName] => Rotavirus [title] => Immunization – Rotavirus [dataType] => Structured_Unstructured [profileId] => 53 [profileDob] => 1992-11-19 ))
[126] => Array ( [0] => Array ( [id] => 4 [docDataName] => Food [title] => Allergy – Food [dataType] => Unstructured [profileId] => 126 [profileDob] => 1988-10-19 ) [2] => Array ( [id] => 3 [docDataName] => ALL [title] => Medication – ALL [dataType] => Unstructured [profileId] => 126 [profileDob] => 1988-10-19 ) [4] => Array ( [id] => 5 [docDataName] => DTaP/DT [title] => Immunization – DTaP/DT [dataType] => Structured_Unstructured [profileId] => 126 [profileDob] => 1988-10-19 )
)
)
here you can see it’s grouped on Basis of 53 and 126, which are only two type of “profileId” in main array.
I am using @ symbol just to surpress warning messges.
It’s an basic idea, you can cutomize function according to your need
Searching in php multidimentional array or array which containing another array
I am a software engineer who specializes in Internet applications. I have worked with a wide variety of technologies and programming languages to open source LAMP environments. I have more than 6 years of object-oriented programming experience and am highly proficient in ActionScript, PHP, MYSQL, JavaScript, Jquery and a multitude of other technologies used in modern web applications.
Follow me
Latest posts by Rajeev Achra (see all)
- Jquery webcam plugin - June 19, 2016
- How To Add and Delete Users on a CentOSServer - June 5, 2016
- How To Set Up vsftpd on CentOS 6 - June 5, 2016