对于每个循环:更改嵌套数组的值
问题描述:
I am having difficulties in changing the values of a nested array. I am trying to change the 'admin' => '1'
value to 'admin' => '0'
of each nested array. I tried a foreach loop but the logic is not correct. How can I correct this? or is there a better way?
Array
'user' => array(
// Regular user, admin
array(
'id' = '1'
'admin' => '1',
),
array(
'id' = '2'
'admin' => '1',
),
array(
'id' = '3'
'admin' => '1',
),
)
Loop:
foreach ($users as $admin => $value) {
if ($value == 1) {
$value == 0;
}
}
答
You need to pass the value by reference if you want to edit it in the source array.
foreach ($users as $admin => &$value) {
if ($value['admin'] == 1) {
$value['admin'] = 0;
}
}
答
You are checking the type of admin twice (==
). You need the assignment statement of =
.
You also need to access the admin
key of the array you are looping on.
This should be more like it:
foreach ($users as $admin => $value) {
if ($value['admin'] == 1) {
// ^ Use ['key'] to access the value of that key
$value['admin'] = '0';
// ^ This assigns 0 to the value.
}
}
答
you forgot to pass 'admin' key for $value in foreach statement
use
$value['admin']