您不能有適合兩種格式的解決方案。隱式數組推式$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.
爲什麼兩種格式,除非這是作業,在這種情況下,標記它,並告訴我們你到目前爲止嘗試過什麼。 – 2012-04-16 11:24:43
您將無法通過推送「更新」現有陣列。我想你或者需要對數組進行foreach,直到找到你想要的或者如果你知道的,直接訪問$ list [1] ['group'] ='new group'; – Analog 2012-04-16 11:25:59
難道你不能只查看你的數組,檢查每個索引中的'name'字段並相應地更新'group'嗎? – Yaniro 2012-04-16 11:26:08