简体   繁体   English

使用PHP更改数组中重复项的值

[英]Changing the value of a repeating item in an array using PHP

I have array 我有阵列

`array(
   [0] =>array(
     [id] => 1,
     [item] => ring,
     [total] => 1000
   ),
   [1] =>array(
     [id] => 1,
     [item] => book,
     [total] => 1000
   ),
   [2] =>array(
     [id] => 1,
     [item] => pen,
     [total] => 400
   )
);`

I need result when [id] is same value only first to show [total] and other need to show - like below please. 我需要结果当[id]是相同的值时才首先显示[total]和其他需要显示-如下所示。

 `array(
  [0] =>array(
     [id] => 1,
     [item] => ring,
     [total] => 1000
   ),
  [1] =>array(
     [id] => 1,
     [item] => book,
     [total] => -
   ),
  [2] =>array(
     [id] => 1,
     [item] => pen,
     [total] => 400
   )
  );`

Thank you for help please. 谢谢你的帮助。

This script might help you to do so: 此脚本可能会帮助您这样做:

$arr = [
    "0" => [
        "id" => "1",
        "item" => "ring",
        "total" => "1000",
    ],
    "1" => [
        "id" => "1",
        "item" => "book",
        "total" => "1000",
    ],
    "2" => [
        "id" => "1",
        "item" => "pen",
        "total" => "400",
    ],
    "3" => [
        "id" => "1",
        "item" => "pen",
        "total" => "400",
    ],
    "4" => [
        "id" => "1",
        "item" => "pen",
        "total" => "400",
    ],
    "5" => [
        "id" => "1",
        "item" => "pen",
        "total" => "500",
    ],
    "6" => [
        "id" => "1",
        "item" => "ring",
        "total" => "1000",
    ],
];

$out_arr = array();
foreach ($arr as $key => $value) {
    array_push($out_arr, $value);
    if ($arr[(int) $key + 1]["total"] && $arr[(int) $key + 1]["id"]) {
        foreach ($arr as $key2 => $value2) {
            if ($value["id"] == $arr[(int) $key2 + 1]["id"] && $value2["total"] == $arr[(int) $key2 + 1]["total"]) {
                $arr[(int) $key + 1]["total"] = '-';
            }
        }

    }
}

var_dump($arr);

Output 产量

array(7) {
  [0]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["item"]=>
    string(4) "ring"
    ["total"]=>
    string(4) "1000"
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["item"]=>
    string(4) "book"
    ["total"]=>
    string(1) "-"
  }
  [2]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["item"]=>
    string(3) "pen"
    ["total"]=>
    string(1) "-"
  }
  [3]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["item"]=>
    string(3) "pen"
    ["total"]=>
    string(1) "-"
  }
  [4]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["item"]=>
    string(3) "pen"
    ["total"]=>
    string(1) "-"
  }
  [5]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["item"]=>
    string(3) "pen"
    ["total"]=>
    string(1) "-"
  }
  [6]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["item"]=>
    string(4) "ring"
    ["total"]=>
    string(1) "-"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM