2015-07-20 33 views
3

我需要扭转的顺序valuesarrayPHP多维array_reverse值

// 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 ] 
    } 

我需要颠倒values保持keys所以它应该是这样的:

​​

我试过没成功:

<?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] 
    }  

*/ 
?> 

这里阅读类似的问题后,也试过以下,但没有成功:

<?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] 
    } 
    ?> 

非常感谢您的宝贵时间。

回答

1

没有测试过,但是这个应该这样做:

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

假设$json是包含您输入,

{"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]} 

考虑这个片段中,

$json = json_decode($json); 

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

$json = json_encode($json); 

现在, $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]}