简体   繁体   中英

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 . For example I want to append 00 in the beginning of the number of [id] . 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:

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. 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:

foreach ($var as &$item) {
    if ($item['visibility'] == 0) {
        $item['id'] = "00{$item['id']}";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM