0

Having some issues parsing my multidimensional php array and removing duplicates. I've spent a good four hours trying to figure out what I'm doing wrong with no luck. If someone could help me out that would wonderful.

Format of multidimensional array: Array(Array("id"=>?, "step_num"=>?, "desc"=>?))

Example data set:

Array(
[0]=> Array([id]=>1, [step_count]=>1, [desc]=>"Something"),
[1]=> Array([id]=>2, [step_count]=>1, [desc]=>"Something New"),
[2]=> Array([id]=>3, [step_count]=>1, [desc]=>"Something Newest")
)

Here's how I am trying to only have the step_count with the most recent desc by comparing id values: ($subStepsFound has the same format as the above array and $results is an empty array to begin with)

foreach($subStepsFound AS $step){

    $found = false;
    $removeEntry = false;
    $index = 0;

    foreach($results AS $key=>$result){

        if($step['step_count'] == $result['step_count']){

            $found = true;

            if($step['id'] > $result['id']){
                $removeEntry = true;
            }
        }

        if($removeEntry === true){
            $index = $key;
        }
    }

    if($removeEntry === true){
        //unset($results[$index]);
        $results[$index] = $step;
    }

    if($found === false){
        $results[] = $step;
    }
}

Expected output of the resulting array:

Array(
    [0]=> Array([id]=>4, [step_count]=>1, [desc]=>"Something Newest")
)
user3459799
  • 345
  • 6
  • 16

2 Answers2

0

See 1., 2., 3. in comments:

foreach($subStepsFound AS $step){

    $found = false;
    $removeEntry = false;
    $index = 0;

    foreach($results AS $key=>$result){

        if($step['step_count'] == $result['step_count']){

            $found = true;

            if($step['id'] > $result['id']){
                $removeEntry = true;
            }
        }

        if($removeEntry === true){
            $results[$key] = $step; // 2. UP TO HERE
            $removeEntry = false;   // 3. RESET $removeEntry
        }
    }

    /*
    if($removeEntry === true){
      //unset($results[$index]);
      $results[$index] = $step; // 1. MOVE THIS...
    }
    */

    if($found === false){
        $results[] = $step;
    }
}

print_r($results);

Online example: http://sandbox.onlinephpfunctions.com/code/1db78a8c08cbee9d04fe1ca47a6ea359cacdd9e9

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37
0
/*super_unique: Removes the duplicate sub-steps found*/
        function super_unique($array,$key){

            $temp_array = array();
            foreach ($array as &$v) {
                if (!isset($temp_array[$v[$key]])) $temp_array[$v[$key]] =& $v;
            }

            $array = array_values($temp_array);

            return $array;
        }

$results = super_unique($subStepsFound, 'step_count');
user3459799
  • 345
  • 6
  • 16