Direak
Direak

Reputation: 55

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.

 `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.

Upvotes: 0

Views: 69

Answers (1)

Emma
Emma

Reputation: 27723

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

Upvotes: 1

Related Questions