I have an associative array as
[name]->user1,
[class_code]->bsc,
[name]->user2,
[class_code]->msc,
[name]->user1,
[class_code]->mca
Now, i want result as
[name]->user1,
[class_code]->bsc,
mca
[name]->user2,
[class_code]->msc
Means if name is same then append the class_code to first one. How should I do that? My array is
[1] =stdClass Object
([class_code] =Maths
[userid] =365
[avatar] =default.jpg
[username] =user2
)
[2] =stdClass Object
(
[class_code] =Maths
[userid] = 364
[avatar] =default.jpg
[username] =user1
)
[3] =stdClass Object
(
[class_code] =MCA
[userid] =364
[avatar] =default.jpg
[username] =user1
)
[4] =stdClass Object
(
[class_code] =MCA
[userid] =365
[avatar] =default.jp开发者_如何转开发g
[username] =user2
)
Now, while displaying result i want to display records of for ex. user2 as
username:user2
avatar
classcode :MCA,Maths
and not
username:user2
avatar
classcode :MCA
username:user2
avatar
classcode :Maths
how can I do that?
You can't have two values with the same key. Otherwise php wouldn't know what to give you if you asked for $myarray['name'].
You could use nested arrays instead.
eg
[0]->
[name]->user1,
[class_code]->bsc,mca,
[1]->
[name]->user2,
[class_code]->msc
or you could do something like this
[user1]->bsc, mca
[user2]->msc
if you want to have both values in there, you should consider using an array in there
array(
"name"=>"user1,
"class_code"=>"array('mca','bsc'),
"name"=>"user2,
"class_code"=>"msc"
);
if [class_code]
must contain a string, you can try
$array[$key] .= $value;
You can make the whole array multidimensional:
$users = array(
0 = array(
"name"=>"user1",
"class_code"=>"bsc"
),
1 = array(
"name"=>"user2",
"class_code"=>"msc"
)
);
Retrieving a value:
$users[1][name] // Returns 'user2'
$users[0][class_code] // Returns 'bsc'
Cycling through values:
foreach($users as $user => $attributes) {
echo "$user: $attributes[name] ($attributes[class_code])<br />";
}
/*
Prints:
0: user1 (bsc)
1: user2 (msc)
*/
精彩评论