我必须处理重构,以减少PHP中的代码行数,以过滤关联数组。 所以我在MySQL中从DB中做出选择,以获得一个关联数组。所以我的对象"有一个类别和一个姓氏领域。
while ($row = mysqli_fetch_array($result)) {
$array[] = $row['category'];
$array[] = $row['Surname'];
}
我想从这个数组中获取,因为许多其他子数组,按类别划分。我的意思是类别数组标识可能是:
$categories = array("A","B","C","D");
所以我想要的是为每个类别获取一个数组,其中包含该类别的所有姓氏。 所以假设该方法有效,可以这样:
$arrayFiltered = method_filter($array_asso,"A");
最后我想要这样的东西:
foreach ($categories as &$value) {
$arrayFiltered = method_filter($array_asso,$value);
my_method_which_needs_the_filtered_array($arrayFiltered);
}
提前感谢您的帮助。
答案 0 :(得分:3)
据我所知 - 您需要一个包含所有surname
category
明智的数组,以便您可以轻松访问它们。这应该有帮助 -
while ($row = mysqli_fetch_array($result)) {
$categories[$row['category']][] = $row['Surname'];
}
只需将类别key
和所有surname
作为值存储到key
。
答案 1 :(得分:1)
警长的方法是最简单的。只是为了它,这是一个array_filter()
的方法(以防万一你必须有一个未经过滤的数组):
$array = [];
$categories = array("A","B","C","D");
while ($row = mysqli_fetch_array($result)) {
$item = [
'category' => $row['category'],
'surname' => $row['Surname']
];
$array[] = $item;
}
$categorized = [];
foreach ($categories as $category) {
$categorized[$category] = array_filter($array, function($item) use ($category) {
return $item['category'] == $category;
});
}
这是一个概念验证,无需数据库连接:
$categories = array("A","B","C","D");
$array = [
['category' => 'A', 'Surname' => 'A Name 1'],
['category' => 'A', 'Surname' => 'A Name 2'],
['category' => 'B', 'Surname' => 'B Name 1'],
['category' => 'B', 'Surname' => 'B Name 2'],
['category' => 'B', 'Surname' => 'B Name 3'],
['category' => 'C', 'Surname' => 'C Name'],
];
$categorized = [];
foreach ($categories as $category) {
$categorized[$category] = array_filter($array, function($item) use ($category) {
return $item['category'] == $category;
});
}
print_r($categorized);
输出:
Array
(
[A] => Array
(
[0] => Array
(
[category] => A
[Surname] => A Name 1
)
[1] => Array
(
[category] => A
[Surname] => A Name 2
)
)
[B] => Array
(
[2] => Array
(
[category] => B
[Surname] => B Name 1
)
[3] => Array
(
[category] => B
[Surname] => B Name 2
)
[4] => Array
(
[category] => B
[Surname] => B Name 3
)
)
[C] => Array
(
[5] => Array
(
[category] => C
[Surname] => C Name
)
)
[D] => Array
(
)
)