我有一个像这样的数组:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1005, "id_user" => 5));
表示5 => 1004, 1005
, 4 => 1000, 1001, 1003
, 3 => 1002
首先,我如何得到这个结构?(可使用逗号)
对于这个解决方案,我的算法是这样的(这就是我要问你们的……如何实现这一点):
$arr = array();
for($i = 0; $i <= count($content) - 1; $i++){
if exists key ($content[$i]['id_user']) IN $arr then
$arr = add_to_existing_key "," . $content[$i]['id_post']
} other wise {
$arr = add_new_key PLUS value $content[$i]['id_user'] <=> $content[$i]['id_post']
}
}
我需要逗号,以便稍后解析信息。基本上,这样做的目的是用$arr
变量做一个循环。假设该数组最后有如下内容:
("id_user" => 5, "ids" => '1004,1005'),
("id_user" => 4, "ids" => '1000,1001,1003'),
("id_user" => 3, "ids" => '1002')
for($i = 0; $i <= count($arr) - 1; $i++){
$ids = explode(",", $arr[$i]['ids']);
$info = array();
for($y = 0; $y <= count($ids) - 1; $y++){
$query->("SELECT * FROM table WHERE id = $ids[$y]");
$info[] = array($name, $description);
}
$email->sendEmail($info); // id = 5 => info OF 1004, 1005
$info = array(); // clear array
// loop
// id = 4 => info OF 1000, 1001, 1003
// loop etc
}
试试这个:
$arr = array();
// Loop through each content
foreach ($content as $post)
{
$arr[$post['id_user']][] = $post['id_post'];
}
这样,结果将是
$arr = array(
'5'=> array('1004', '1005'),
'4'=> array('1000', '1001', '1003'),
'3'=> array('1002')
);
那么你就不需要使用" explosion "来分割那些以逗号分隔的id了还
我认为你最好坚持使用数组,而不是用逗号连接,然后再使用exploding
:
foreach($content as $values) {
if(!isset($result[$values['id_user']])) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
print_r($result);
可能这个变体正是您所需要的:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1005, "id_user" => 5));
// Make preparation array
foreach ( $content as $values ) {
if ( !isset($result[$values['id_user']]) ) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
// Sort inner arrays
foreach ( $result as $key => $valueArray ) {
asort($result[$key]);
}
// Implode arrays to strings
array_walk($result, function(&$array, $key) {
$array = implode(',', $array);
});
// Final array
$result1 = array();
foreach ( $result as $userID => $idsString ) {
$result1[] = array("id_user" => $userID, "id_post" => $idsString);
}
print_r($result1);