2012-04-16 22 views
-1
$list = array(
       [0]=> array(
          [name]=>'James' 
          [group]=>'' 
         ) 
       [1]=> array(
          [name]=>'Bobby' 
          [group]=>'' 
         ) 
      ) 

我在找更新名为'Bobby'的项目'group'。我正在寻找具有以下两种格式的解决方案。预先感谢您的回复。干杯。马克。PHP - 如何在一些条件下追加数组

array_push($list, ???) 

$list[] ??? = someting 
+0

为什么两种格式,除非这是作业,在这种情况下,标记它,并告诉我们你到目前为止尝试过什么。 – 2012-04-16 11:24:43

+0

您将无法通过推送“更新”现有阵列。我想你或者需要对数组进行foreach,直到找到你想要的或者如果你知道的,直接访问$ list [1] ['group'] ='new group'; – Analog 2012-04-16 11:25:59

+0

难道你不能只查看你的数组,检查每个索引中的'name'字段并相应地更新'group'吗? – Yaniro 2012-04-16 11:26:08

回答

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版本的方法。

+0

你好西蒙,谢谢你... – Marc 2012-04-16 11:31:41

0

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

此代码可以帮助你:

$listSize = count($list); 

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

array_push()并不真的只涉及到更新的值,它给数组增加了另一个值。