-1
$list = array(
               [0]=> array(
                            [name]=>'James' 
                            [group]=>''
                          )
               [1]=> array(
                            [name]=>'Bobby' 
                            [group]=>''
                          )
             )

名前が「Bobby」である項目「group」を更新しようとしています。次の2つの形式のソリューションを探しています。返信ありがとうございます。乾杯。マーク。

array_push($list, ???)

$list[] ??? = someting
4

3 に答える 3

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 を使用する方法も記載されています。

于 2012-04-16T11:28:20.520 に答える
1

このコードはあなたを助けるかもしれません:

$listSize = count($list);

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

array_push()値の更新には実際には関係ありません。配列に別の値を追加するだけです。

于 2012-04-16T11:38:24.593 に答える
0

両方の形式に適合するソリューションはありません。暗黙の配列プッシュ$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.
于 2012-04-16T11:34:09.613 に答える