我有一个名为$classes_data
的关联数组,如下所示:
Array
(
[2] => Array
(
[class_id] => 2
[class_name] => II
[subjects] => Array
(
[0] => 11 Engllish
)
)
[3] => Array
(
[class_id] => 3
[class_name] => III
[subjects] => Array
(
[0] => Hidi
[1] => 11 Maths
[2] => 11 Science
[3] => 11 Engllish
)
)
[4] => Array
(
[class_id] => 4
[class_name] => IV
[subjects] => Array
(
[0] => Physics
)
)
[6] => Array
(
[class_id] => 6
[class_name] => VI
[subjects] => Array
(
[0] => Mathematics
[1] => dfadadadsagfasrsarasrarBiology
)
)
[7] => Array
(
[class_id] => 7
[class_name] => VII
[subjects] => Array
(
[0] => Physics
[1] => Chemistry11
[2] => 11 Science
)
)
[8] => Array
(
[class_id] => 8
[class_name] => VIII
[subjects] => Array
(
[0] => Hidi
[1] => 11 Engllish
)
)
[9] => Array
(
[class_id] => 9
[class_name] => IX
[subjects] => Array
(
[0] => Mathematics
[1] => Hidi
[2] => 11 Science
)
)
)
数组的键(即2,3,4,6,7,8,9)以这种方式而不是0,1,2,3,4,5,6,因为我使用了一个函数重新排列这些键。
现在我要做的是插入一个新密钥class_checked
并将其初始值设置为0
(即class_checked =>"0"
)。
我尝试了许多技巧但无法获得所需的数组格式。任何人都可以帮助我获得所需的阵列吗?提前谢谢。
对于您的信息,数组$classes_data
所需的数组格式如下:
Array
(
[2] => Array
(
[class_id] => 2
[class_name] => II
[class_checked] => 0
[subjects] => Array
(
[0] => 11 Engllish
)
)
[3] => Array
(
[class_id] => 3
[class_name] => III
[class_checked] => 0
[subjects] => Array
(
[0] => Hidi
[1] => 11 Maths
[2] => 11 Science
[3] => 11 Engllish
)
)
[4] => Array
(
[class_id] => 4
[class_name] => IV
[class_checked] => 0
[subjects] => Array
(
[0] => Physics
)
)
[6] => Array
(
[class_id] => 6
[class_name] => VI
[class_checked] => 0
[subjects] => Array
(
[0] => Mathematics
[1] => dfadadadsagfasrsarasrarBiology
)
)
[7] => Array
(
[class_id] => 7
[class_name] => VII
[class_checked] => 0
[subjects] => Array
(
[0] => Physics
[1] => Chemistry11
[2] => 11 Science
)
)
[8] => Array
(
[class_id] => 8
[class_name] => VIII
[class_checked] => 0
[subjects] => Array
(
[0] => Hidi
[1] => 11 Engllish
)
)
[9] => Array
(
[class_id] => 9
[class_name] => IX
[class_checked] => 0
[subjects] => Array
(
[0] => Mathematics
[1] => Hidi
[2] => 11 Science
)
)
)
答案 0 :(得分:4)
尝试:
foreach($classes_data as $key=>$value) {
$classes_data[$key]['class_checked'] = 0;
}
答案 1 :(得分:3)
$array = array_map(function (array $i) { return $i + array('class_checked' => 0); }, $array);
或者:
foreach ($array as &$i) {
$i['class_checked'] = 0;
}
unset($i);
答案 2 :(得分:0)
鉴于您的初始$classes_data
,您可以这样做:
foreach($classes_data as &$class) {
$class['class_checked'] = 0;
}
现在数组应该是您想要的。