2016-04-21 92 views
1

我有這個變量是我的查詢結果:如何更改基於另一個鍵的數組鍵的值?

Array(
     [0] => Array 
     (
      [id] => 1 
      [visibility] => 0 
     ) 

     [2] => Array 
     (
      [id] => 2 
      [visibility] => 1 
     ) 

     [3] => Array 
     (
      [id] => 3 
      [visibility] => 0 
     ) 
) 

現在我想改變[id]項目的數量時,其[visibility]0。例如,我想在[id]的數字的開頭追加00。這是預期的輸出:

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

回答

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); 
    ?> 
2

稍微容易引用$item並改變它:

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

參考是:http://php.net/manual/en/language.references.php還有一個例如在http://php.net/manual/en/control-structures.foreach.php – AbraCadaver

+0

'$ item'是''var'中每個數組的引用'&',所以它的工作原理是。 – AbraCadaver

+0

哦..是的,你是對的。 – stack

相關問題