[英]How can I change the value of key of array base on another key?
I have this variable which is the result of my query: 我有这个变量,这是我的查询结果:
Array(
[0] => Array
(
[id] => 1
[visibility] => 0
)
[2] => Array
(
[id] => 2
[visibility] => 1
)
[3] => Array
(
[id] => 3
[visibility] => 0
)
)
Now I want to change the number of [id]
item when its [visibility]
is 0
. 现在,我想在
[id]
项目的[visibility]
为0
时更改其数量。 For example I want to append 00
in the beginning of the number of [id]
. 例如,我想在
[id]
的开头添加00
。 This is expected output: 这是预期的输出:
Array(
[0] => Array
(
[id] => 001
[visibility] => 0
)
[2] => Array
(
[id] => 2
[visibility] => 1
)
[3] => Array
(
[id] => 003
[visibility] => 0
)
)
How can I do that? 我怎样才能做到这一点?
I can check the value of visibility
like this: 我可以这样检查
visibility
的值:
foreach ($var as $item) {
if ($item['visibility'] == 0) {
// I need to append two zero before the number of its id
}
}
You started foreach
and correct condition check but didn't write any code inside it. 您开始
foreach
并更正了条件检查,但未在其中编写任何代码。 Check below:- 检查以下:-
<?php
foreach ($var as $key=> $item) {
if ($item['visibility'] == 0) { // if visibility is 0
$var[$key]['id'] = "00". $var[$key]['id']; // add 00 to corresponding id in the original array
}
}
echo "<pre/>";print_r($var);
?>
Slightly easier to reference $item
and change it: 稍微容易引用
$item
并进行更改:
foreach ($var as &$item) {
if ($item['visibility'] == 0) {
$item['id'] = "00{$item['id']}";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.