你们无法找到既适合这两种方式的解决办法。 暗中阵列的推导号$var[]
是一个合成构造,你不能发明新的构体——当然不是在PHP,也不是大多数(所有)其他语文。
除此之外,你正在做的是而不是把一个项目推向阵列。 一种情况是,推进项目意味着一个指数化阵列(约会是一种联系),而另一个推论意味着增加阵列的关键(你想要更新的关键已经存在)。
You can write a function to do it, something like this:
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.