while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$basicinfo[] = array('schlid' => $selected_row['schlid'], 'name' => $selected_row['name'], 'class' => $selected_row['class']);
}
上面的构造数组将得到一个有多个值的数组,数组看起来像这样
Array
(
[0] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => Math
)
[1] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => English
)
[2] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => Math
)
[3] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => English
)
[4] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => Math
)
[5] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => English
)
[6] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => Math
)
[7] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => English
)
[8] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => Math
)
[9] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => English
)
[10] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => Math
)
[11] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => English
)
)
但是我可以通过在
下面执行此操作来删除相同的值$input = array_map("unserialize", array_unique(array_map("serialize", $basicinfo)));
$new_data = array_values($input);
我将在
下面得到这个Array
(
[0] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => Math
)
[1] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[class] => English
)
)
现在我所做的是创建一个多维数组的相同的查询结果
while ($selected_row = $stmt - > fetch(PDO::FETCH_ASSOC)) {
$tmp_key = $selected_row['schlid']; //adding a temp key
$basicinfo[$tmp_key]['name'] = $selected_row['name'];
$basicinfo[$tmp_key]['schlid'] = $selected_row['schlid'];
$sudky = (isset($basicinfo[$tmp_key]['Class'])) ? count($basicinfo[$tmp_key]['Class']) : 0;
$basicinfo[$tmp_key]['Class'][$sudky]['class'] = $selected_row['class'];
}
从上面得到的结果是
Array
(
[015-08-0011-000-01] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[Class] => Array
(
[0] => Array
(
[class] => Math
)
[1] => Array
(
[class] => English
)
[2] => Array
(
[class] => Math
)
[3] => Array
(
[class] => English
)
[4] => Array
(
[class] => Math
)
[5] => Array
(
[class] => English
)
[6] => Array
(
[class] => Math
)
[7] => Array
(
[class] => English
)
[8] => Array
(
[class] => Math
)
[9] => Array
(
[class] => English
)
[10] => Array
(
[class] => Math
)
[11] => Array
(
[class] => English
)
)
)
)
My desired out is
Array
(
[015-08-0011-000-01] => Array
(
[schlid] => 015-08-0011-000-01
[name] => John
[Class] => Array
(
[0] => Array
(
[class] => Math
)
[1] => Array
(
[class] => English
)
)
)
)
删除多维数组中的重复元素。上面的结果来自php中的print_r()
您可以使用for
loop在分配学生类之前检查,或者在输出之后使用array_unique处理包含重复类的数组。
$basicinfo[$tmp_key]['Class'][0] = array_unique($basicinfo[$tmp_key]['Class'][0]); //<-The array that you don't want duplicates in. i modify the formating