1

我想比较数组中的键值,如果找到匹配则增加元素的值。

为此,我使用代码:

// var_dump $all_array 
array(2) { 
    [0]=> array(6) { 
        [0]=> string(8) "art_7880"
        [1]=> string(11) "Арт.7880"
        [2]=> string(1) "1"
        [3]=> NULL
        [4]=> string(45) "png"
        [5]=> int(1372269755) 
    } 
    [1]=> array(6) { 
         [0]=> string(8) "art_7880"
         [1]=> string(11) "Арт.7880"
         [2]=> string(1) "1"
         [3]=> NULL
         [4]=> string(45) "png"
         [5]=> int(1372269874) 
    } 
}
// var_dump $count 
array(2) { [0]=> string(2) "10" [1]=> string(1) "1" }

// var_dump $product
array(2) { [0]=> string(10) "1372269755" [1]=> string(10) "1372269874" }

$count=$_POST['count'];
$product=$_POST['product'];
$count_arr_products=count($product);

for ($i=0; $i<=$count_arr_products; $i++){    
    foreach ($all_array as $keys => $elms) {
        if ($product[$i]==$elms[5]) {
            if($count[$i] > 0) {
                $elms[2] = $count[$i];
            } else {
                unset($keys);
            }
        }
    }
}

但步骤$elms[2] = $count[$i];不起作用 - 结果值$elms[2]不会改变......

4

1 回答 1

3

你需要做$elms一个参考。默认情况下,它将是子数组的副本,因此分配不会更新原始数组。

$all_array = array(array("art_7880", "Арт.7880", "1", NULL, "png", 1372269755),
                   array("art_7880", "Арт.7880", "1", NULL, "png", 1372269874));
$count = array("10", "1");
$product = array("1372269755", "1372269874");

$count = array("10", "1");
$product = array("1372269755", "1372269874");
$count_arr_products = count($product);
for($i=0; $i<$count_arr_products; $i++){ // Use < not <=
  foreach ($all_array as $keys => &$elms) { // Use a reference so we can update it
    if ($product[$i]==$elms[5]){
      if ($count[$i] > 0) {
        $elms[2] = $count[$i];
      } else {
        unset($all_array[$keys]); // not unset($keys)
      }
    }
  }
}
var_dump($all_array);

输出:

array(2) {
  [0]=>
  array(6) {
    [0]=>
    string(8) "art_7880"
    [1]=>
    string(11) "Арт.7880"
    [2]=>
    string(2) "10"
    [3]=>
    NULL
    [4]=>
    string(3) "png"
    [5]=>
    int(1372269755)
  }
  [1]=>
  &array(6) {
    [0]=>
    string(8) "art_7880"
    [1]=>
    string(11) "Арт.7880"
    [2]=>
    string(1) "1"
    [3]=>
    NULL
    [4]=>
    string(3) "png"
    [5]=>
    int(1372269874)
  }
}
于 2013-06-26T18:48:52.757 回答