両方の形式に適合するソリューションはありません。暗黙の配列プッシュ$var[]
は構文構造であり、新しいものを発明することはできません - 確かに PHP ではなく、ほとんどの (すべて?) 他の言語でもそうではありません。
それとは別に、あなたがしているのは、アイテムを配列にプッシュすることではありません。1 つには、アイテムをプッシュすることはインデックス付き配列を意味し (あなたのものは連想配列です)、別の場合には、プッシュすることは配列にキーを追加することを意味します (更新したいキーは既に存在します)。
次のような関数を書くことができます。
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.