PHP Multidimensional values โ€‹โ€‹array_reverse

I need to reverse the order values

in array

:

// My current array looks like this
// echo json_encode($array);

    { "t" : [ 1, 2, 3, 4, 5, 6 ],
      "o" : [ 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 ],
      "h" : [ 1.2, 2.2, 3.2, 4.2, 5.2, 6.2 ]
     }

      

I need to invert values

while saving keys

so it looks like this:

// echo json_encode($newArray);

    { "t" : [6, 5, 4, 3, 2, 1 ],
      "o" : [ 6.6, 5.5, 4.4, 3.3, 2.2, 1.1],
      "h" : [ 6.2, 5.2, 4.2, 3.2, 2.2, 1.2 ]
     }

      

What I have tried without success:

<?php
$newArray= array_reverse($array, true);
echo json_encode($newArray);
/* The above code output (Note that the values keep order):
  {
    "h":[1.2, 2.2, 3.2, 4.2, 5.2, 6.2]
    "o":[1.1, 2.2, 3.3, 4.4, 5.5, 6.6]
    "t":[1,2,3,4,5,6]
   }       

*/
 ?>

      

After reading a similar question here also tried the following but with no success:

<?php
$k = array_keys($array);

$v = array_values($array);

$rv = array_reverse($v);

$newArray = array_combine($k, $rv);

echo json_encode($b);

/* The above code change association of values = keys, output:
  { "h": [1.1, 2.2, 3.3, 4.4, 5.5, 6.6],
    "o": [1,2,3,4,5,6],
    "t": [1.2, 2.2, 3.2, 4.2, 5.2, 6.2]
  }
  ?>

      

Thanks a lot for your time.

+3


source to share


2 answers


Haven't tested, but this should do it:



$newArray = array();
foreach($array as $key => $val) {
    $newArray[$key] = array_reverse($val);
}

      

+1


source


Assuming $json

- your input containing

{"t":[1,2,3,4,5,6],"o":[1.1,2.2,3.3,4.4,5.5,6.6],"h":[1.2,2.2,3.2,4.2,5.2,6.2]}

      

Consider this snippet,



$json = json_decode($json);

$json = array_map('array_reverse', get_object_vars($json));

$json = json_encode($json);

      

Now $json

contains

{"t":[6,5,4,3,2,1],"o":[6.6,5.5,4.4,3.3,2.2,1.1],"h":[6.2,5.2,4.2,3.2,2.2,1.2]}

      

0


source







All Articles