如何在另一个键上更改数组的键值?

时间:2016-04-21 18:19:21

标签: php arrays

我有这个变量,这是我查询的结果:

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
    }
}

2 个答案:

答案 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']}";
    }
}