我有这个变量,这是我查询的结果:
Array(
[0] => Array
(
[id] => 1
[visibility] => 0
)
[2] => Array
(
[id] => 2
[visibility] => 1
)
[3] => Array
(
[id] => 3
[visibility] => 0
)
)
现在,我希望在[id]
为[visibility]
时更改0
项的数量。例如,我想在00
的数字的开头附加[id]
。这是预期的输出:
Array(
[0] => Array
(
[id] => 001
[visibility] => 0
)
[2] => Array
(
[id] => 2
[visibility] => 1
)
[3] => Array
(
[id] => 003
[visibility] => 0
)
)
我该怎么做?
我可以像这样检查visibility
的值:
foreach ($var as $item) {
if ($item['visibility'] == 0) {
// I need to append two zero before the number of its id
}
}
答案 0 :(得分:3)
您启动了foreach
并更正了条件检查,但未在其中写入任何代码。检查以下内容: -
<?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);
?>
答案 1 :(得分:2)
稍微更容易引用$item
并更改它:
foreach ($var as &$item) {
if ($item['visibility'] == 0) {
$item['id'] = "00{$item['id']}";
}
}