How right replace value element in array?

后端 未结 1 1283
Happy的楠姐
Happy的楠姐 2021-01-07 12:11

I want to compare the key values ​​in the array and if a match is found to increase the value of the element.

For this I use code:

// var_dump $all_a         


        
1条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 12:58

    You need to majke $elms a reference. By default it will be a copy of the sub-array, so assignment won't update the original array.

    $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);
    

    Output:

    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)
      }
    }
    

    0 讨论(0)
提交回复
热议问题