3

I need to reverse the order of the 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 the values keeping the keys so it should look 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 similar question here, also tried the following but without 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]
  }
  ?>

Thank you very much for your time.

2 Answers 2

1

Haven't tested it, but this should do it:

$newArray = array();
foreach($array as $key => $val) {
    $newArray[$key] = array_reverse($val);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming $json is 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]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.