您不能有适合两种格式的解决方案。隐式数组推式$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