PHP : Replacing keys with incremental integer

Viewed 53

I have this stdClass Object

Array ( 
[0] => stdClass Object ( [criteria1] => 1 [criteria2] => 2 [criteria3] => 2 ) 
[1] => stdClass Object ( [criteria1] => 2 [criteria2] => 1 [criteria3] => 1 ) 
[2] => stdClass Object ( [criteria1] => 1 [criteria2] => 1 [criteria3] => 1 ) 
)

I want to replace the keys into an integer like below

Array ( 
[0] => stdClass Object ( [0] => 1 [1] => 2 [2] => 2 ) 
[1] => stdClass Object ( [0] => 2 [1] => 1 [2] => 1 ) 
[2] => stdClass Object ( [0] => 1 [1] => 1 [2] => 1 ) 
)

Then I add this function, $arr is for the array of object, $len is for the number of columns of the array

            function replace_key($arr,$len) {
              $temp_array = array();

              foreach ($arr as $key => $val) {
                $object = new stdClass();
                $x = (array) $val;

               foreach ($x as $key2 => $value) {
                    for ($i=0; $i < $len; $i++) { 
                        $new_key = $i;
                        $object->$new_key = $value;
                        }
                    }
                $temp_array[] = $object;
              }
              return $temp_array;
            }

But it resulted this output (the keys are already like how I want but the values are all wrong)

Array ( 
[0] => stdClass Object ( [0] => 2 [1] => 2 [2] => 2 ) 
[1] => stdClass Object ( [0] => 1 [1] => 1 [2] => 1 ) 
[2] => stdClass Object ( [0] => 1 [1] => 1 [2] => 1 ) 
)

I have no idea what part I did it wrong, I already tried to fix it for several hours but nothing seemed to workout and that function code is far the best I could do. Please help me, I'm so stucked.

2 Answers

Try this code

<?php
    $a = (object)array("criteria1"=>1,"criteria2"=>2,"criteria3"=>2);
    $b = (object)array("criteria1"=>2,"criteria2"=>1,"criteria3"=>1);
    $c = (object)array("criteria1"=>1,"criteria2"=>1,"criteria3"=>1);
    $test = array($a, $b,$c);
  
    function replace_key($arr) {
        foreach ($arr as $key => $val) {
            $object =array();
            $object =array_values((array)$val);
            $temp_array[] = (object)$object;
       }
      return $temp_array;
    }

    print_r(replace_key($test));
?>

working code

   function replace_key($arr, $len = null)
    {
        $results = [];
        foreach ($arr as $ar) {
            $array = array_values((array)$ar);
            $results[] = (object)array_slice($array, 0, $len);
        }
        return $results;
    }
Related