Home > Enterprise >  giving same row number to duplicate value in array with php
giving same row number to duplicate value in array with php

Time:01-08

i have this array

$state_point_array = array("Tehran"=>"8400", "Qazwin"=>"4960", "Fars"=>"1600","Booshehr"=>"1600","Khorasan"=>"1600","Bandar"=>"1080");

i used foreach :


$D=0;
foreach($state_point_array as $key=>$val){
    $D  ;
echo $D.' | '.$key.' | '.$val.'<br>';
 }

and here is my output:

1 | Tehran | 8400
2 | Qazwin | 4960
3 | Fars | 1600
4 | Booshehr | 1600
5 | Khorasan | 1600
6 | Bandar | 1080

i want to give same row number to duplicate values like this:

1 | Tehran | 8400
2 | Qazwin | 4960
3 | Fars | 1600
3 | Booshehr | 1600
3 | Khorasan | 1600
4 | Bandar | 1080

I tried array_unique but it didn't work as i want, it just count the duplicates.Thanks for any help

CodePudding user response:

You could keep track of the $D value in a separate array and check if it exists per iteration. If it does not, then increment the value and add it to the array.

$state_point_array = array("Tehran" => "8400", "Qazwin" => "4960", "Fars" => "1600", "Booshehr" => "1600", "Khorasan" => "1600", "Bandar" => "1080", "test" => "1600", "test2" => "8400");
$D = 0;
$values = [];

foreach ($state_point_array as $key => $val) {
    if (!array_key_exists($val, $values)) {
        $values[$val] =   $D;
    } else {
        $D = $values[$val];
    }
    echo $D . ' | ' . $key . ' | ' . $val . '<br>';
}

Output

1 | Tehran | 8400
2 | Qazwin | 4960
3 | Fars | 1600
3 | Booshehr | 1600
3 | Khorasan | 1600
4 | Bandar | 1080
3 | test | 1600
1 | test2 | 8400

CodePudding user response:

$state_point_array = array("Tehran"=>"8400", "Qazwin"=>"4960", "Fars"=>"1600","Booshehr"=>"1600","Khorasan"=>"1600","Bandar"=>"1080");

function group_by_val($array) {
    $res = [];
    foreach($array as $key => $val) {
        $res[$val][$key] = $val;
    }
    return $res;
}

$newArr = group_by_val($state_point_array);

// Only if you want to sort the array.
// ksort($newArr);
// krsort($newArr);

$D=0;
foreach ($newArr as $key => $val) {
    $D  ;
    foreach ($val as $k => $v) {
        echo $D.' | '.$k.' | '.$v.'<br>';
    }
}
  • Related