2012-04-16 24 views
-1
$list = array(
       [0]=> array(
          [name]=>'James' 
          [group]=>'' 
         ) 
       [1]=> array(
          [name]=>'Bobby' 
          [group]=>'' 
         ) 
      ) 

我在找更新名爲'Bobby'的項目'group'。我正在尋找具有以下兩種格式的解決方案。預先感謝您的回覆。乾杯。馬克。PHP - 如何在一些條件下追加數組

array_push($list, ???) 

$list[] ??? = someting 
+0

爲什麼兩種格式,除非這是作業,在這種情況下,標記它,並告訴我們你到目前爲止嘗試過什麼。 – 2012-04-16 11:24:43

+0

您將無法通過推送「更新」現有陣列。我想你或者需要對數組進行foreach,直到找到你想要的或者如果你知道的,直接訪問$ list [1] ['group'] ='new group'; – Analog 2012-04-16 11:25:59

+0

難道你不能只查看你的數組,檢查每個索引中的'name'字段並相應地更新'group'嗎? – Yaniro 2012-04-16 11:26:08

回答

1

據我所知,沒有辦法更新與給定語法的一個您的數組。

唯一類似的事情我可以來使用array_walk是循環陣列之上... http://www.php.net/manual/en/function.array-walk.php

實施例:

array_walk($list, function($val, $key) use(&$list){ 
    if ($val['name'] == 'Bobby') { 
     // If you'd use $val['group'] here you'd just editing a copy :) 
     $list[$key]['group'] = "someting"; 
    } 
}); 

編輯:實施例是使用匿名功能,這僅僅是可能的,因爲PHP 5.3。文檔還提供了使用舊版PHP版本的方法。

+0

你好西蒙,謝謝你... – Marc 2012-04-16 11:31:41

0

您不能有適合兩種格式的解決方案。隱式數組推式$var[]是一種語法結構,您不能創造新的 - 當然不是在PHP中,也不是大多數(所有?)其他語言。

除此之外,您正在做的是而不是將一個項目推到陣列上。首先,推送項目意味着一個索引數組(你的關聯),而另一個推送意味着向數組添加一個鍵(你想要更新的鍵已經存在)。

您可以編寫一個函數來做到這一點,是這樣的:

function array_update(&$array, $newData, $where = array(), $strict = FALSE) { 
    // Check input vars are arrays 
    if (!is_array($array) || !is_array($newData) || !is_array($where)) return FALSE; 
    $updated = 0; 
    foreach ($array as &$item) { // Loop main array 
    foreach ($where as $key => $val) { // Loop condition array and compare with current item 
     if (!isset($item[$key]) || (!$strict && $item[$key] != $val) || ($strict && $item[$key] !== $val)) { 
     continue 2; // if item is not a match, skip to the next one 
     } 
    } 
    // If we get this far, item should be updated 
    $item = array_merge($item, $newData); 
    $updated++; 
    } 
    return $updated; 
} 

// Usage 
$newData = array(
    'group' => '???' 
); 
$where = array(
    'name' => 'Bobby' 
); 

array_update($list, $newData, $where); 

// Input $array and $newData array are required, $where array can be omitted to 
// update all items in $array. Supply TRUE to the forth argument to force strict 
// typed comparisons when looking for item(s) to update. Multiple keys can be 
// supplied in $where to match more than one condition. 

// Returns the number of items in the input array that were modified, or FALSE on error. 
1

此代碼可以幫助你:

$listSize = count($list); 

for($i = 0; $i < $listSize; ++$i) { 
    if($list[$i]['name'] == 'Bobby') { 
     $list[$i]['group'] = 'Hai'; 
    } 
} 

array_push()並不真的只涉及到更新的值,它給數組增加了另一個值。