全部,
我有以下数组和函数,它将根据您指定的数组键创建一个多维数组。对于传递给函数的每个属性,它都会向数组添加另一个维度。将其视为数组排序。
提供的函数很好用,但它使用 eval,我很难想出一个一致的函数,没有它就不会出错。
让我们从一个数组开始:
$array = array(
array(‘name’ => ‘Person1’, ‘username’ => ‘username1’, ‘join_date’ => 12233445566, ‘state’ => ‘NJ’),
array(‘name’ => ‘Person2’, ‘username’ => ‘username2’, ‘join_date’ => 12233445566, ‘state’ => ‘NJ’),
array(‘name’ => ‘Person3’, ‘username’ => ‘username3’, ‘join_date’ => 12233445996, ‘state’ => ‘NY’),
array(‘name’ => ‘Person4’, ‘username’ => ‘username4’, ‘join_date’ => 12233445996, ‘state’ => ‘NJ’),
array(‘name’ => ‘Person5’, ‘username’ => ‘username5’, ‘join_date’ => 12233445566, ‘state’ => ‘NJ’),
array(‘name’ => ‘Person6’, ‘username’ => ‘username6’, ‘join_date’ => 12233445566, ‘state’ => ‘NY’),
array(‘name’ => ‘Person7’, ‘username’ => ‘username7’, ‘join_date’ => 12233445776, ‘state’ => ‘NY’),
array(‘name’ => ‘Person8’, ‘username’ => ‘username8’, ‘join_date’ => 12233445566, ‘state’ => ‘NY’),
array(‘name’ => ‘Person9’, ‘username’ => ‘username9’, ‘join_date’ => 12233445996, ‘state’ => ‘NJ’),
);
这是一个示例函数:
function createIndex($array, $index){
$index_array = array();
foreach($array as $result){
if(is_array($index)){
$key = '$index_array';
for($i=0;$i<=sizeof($index)-1;$i++){
$key .= "['{$result[$index[$i]]}']";
}
$key .= "[]";
eval("$key = \$result;");
}
else{
$index_array[$result[$index]] = $result;
}
}
return $index_array;
}
调用函数:
print_r(create_index($array, array(‘state’, ‘join_date’)));
所需的输出:
Array
(
[NJ] => Array
(
[12233445566] => Array
(
[0] => Array
(
[name] => Person1
[username] => username1
[join_date] => 12233445566
[state] => NJ
)
[1] => Array
(
[name] => Person2
[username] => username2
[join_date] => 12233445566
[state] => NJ
)
[2] => Array
(
[name] => Person5
[username] => username5
[join_date] => 12233445566
[state] => NJ
)
)
[12233445996] => Array
(
[0] => Array
(
[name] => Person4
[username] => username4
[join_date] => 12233445996
[state] => NJ
)
[1] => Array
(
[name] => Person9
[username] => username9
[join_date] => 12233445996
[state] => NJ
)
)
)
[NY] => Array
(
[12233445996] => Array
(
[0] => Array
(
[name] => Person3
[username] => username3
[join_date] => 12233445996
[state] => NY
)
)
[12233445566] => Array
(
[0] => Array
(
[name] => Person6
[username] => username6
[join_date] => 12233445566
[state] => NY
)
[1] => Array
(
[name] => Person8
[username] => username8
[join_date] => 12233445566
[state] => NY
)
)
[12233445776] => Array
(
[0] => Array
(
[name] => Person7
[username] => username7
[join_date] => 12233445776
[state] => NY
)
)
)
)
问题:有什么方法可以克服上述问题以从相同的数组中获得相同的结果?我很好奇其他人会怎么做。
谢谢