0
我有以下陣列如何通過comon值組合數組?
Array
(
[0] => Array
(
[section_name] => phone_calls
[0] => phone_calls
[permission_key] => can_delete
[1] => can_delete
[requirment] => 000000000100000
[2] => 000000000100000
)
[1] => Array
(
[section_name] => phone_calls
[0] => phone_calls
[permission_key] => can_insert
[1] => can_insert
[requirment] => 000000000001000
[2] => 000000000001000
)
[2] => Array
(
[section_name] => phone_calls
[0] => phone_calls
[permission_key] => can_purge
[1] => can_purge
[requirment] => 000000000010000
[2] => 000000000010000
)
[3] => Array
(
[section_name] => phone_calls
[0] => phone_calls
[permission_key] => can_update
[1] => can_update
[requirment] => 000000000000100
[2] => 000000000000100
)
[4] => Array
(
[section_name] => accounts
[0] => phone_calls
[permission_key] => can_use
[1] => can_use
[requirment] => 000000000000001
[2] => 000000000000001
)
[5] => Array
(
[section_name] => accounts
[0] => phone_calls
[permission_key] => can_view
[1] => can_view
[requirment] => 000000000000010
[2] => 000000000000010
)
)
我希望它看起來像這樣
Array
(
[phone_calls] => Array
(
[can_update] => 4
[can_insert] => 8
[can_purge] => 16
[can_delete] => 32
)
[accounts] => Array
(
[can_use] => 1
[can_view] => 2
)
)
這裏,共同的因素是「SECTION_NAME」的值,只要「secton_name」是一樣的,然後permission_key和需求進入同一個桶。
在這個例子中,有2個不同的SECTION_NAME(即phone_calls,帳戶),以便最終的陣列應具有2個鍵(即phone_calls,帳戶)
這是我迄今嘗試
$rules = getSystemRules();
$rulesTotal = count($rules);
$finalArray = array();
$subArray = array();
for($i=0; $i < $rulesTotal; ++$i){
$row = $rules[$i];
/** if section_name = the previous section_name then put the the "permission_key" and the "requirment"
* in the same array $subArray. Else take the $subArray and put it into a new array called $finalArray
* and make they key for the $finalArray the section_name
*/
if($i == 0 || ($i > 0 && $row['section_name'] == $rules[$i-1]['section_name'])){
$subArray[$row['permission_key']] = bindec($row['requirment']);
} else {
$finalArray[$rules[$i-1]['section_name']][] = $subArray;
$subArray = array();
$subArray[$row['permission_key']] = bindec($row['requirment']);
}
}
print_r($finalArray);
這是查詢我的用戶獲得$rules
陣列
SELECT SQL_CACHE section_name, permission_key, requirement
FROM permission_rules
ORDER BY section_name
但這種代碼是不工作像我期望的那樣。該$finalArray
總是空
也許你的SQL查詢的一個小小的變化可能會給你一個更接近你想要的格式 – 2014-12-04 00:13:58