我有一些foreach
的脚本,见下文,
我的每个人总是从我的json对象中显示输出2 - 1 - 3 - 4 - 等,如何解决我的问题,?
<?php public function renderLayout3x3($data=array()){
$output = "<ul>";
foreach ($data as $key => $value) {
if($value['posisi'] == '1'){
$output .= "<li><ul>
<li>POS:".$value['posisi']."</li>
<li>HOSTNAME:".$value['hostname']."</li>
</ul></li>";
}
if($value['posisi'] == '2'){
$output .= "<li><ul>
<li>POS:".$value['posisi']."</li>
<li>HOSTNAME:".$value['hostname']."</li>
</ul></li>";
}
if($value['posisi'] == '3'){
$output .= "<li><ul>
<li>POS:".$value['posisi']."</li>
<li>HOSTNAME:".$value['hostname']."</li>
</ul></li>";
}
//for debug..
print json_encode($value['posisi']);
/*
Output : "2","1","3","4","5","6","7","8","9"
Why : 2 - 1 - 3 - etc, not 1 - 2 - 3 - etc
*/
}
$output .= "</ul>";
return $output;
}
$json_data = '{"ch":"79",
"ipaddr":"172.16.11.100",
"hostname":"TMC-MALL01",
"posisi":"2",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}{
"ch":"78",
"ipaddr":"172.16.11.99",
"hostname":"TMC-JSB01",
"posisi":"1",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}{
"ch":"80",
"ipaddr":"172.16.11.101",
"hostname":"TMC-MALL02",
"posisi":"3",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}{
"ch":"92",
"ipaddr":"172.16.11.106",
"hostname":"TMC-PALMA01",
"posisi":"4",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}{
"ch":"93",
"ipaddr":"172.16.11.107",
"hostname":"TMC-PALMA02",
"posisi":"5",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}{
"ch":"112",
"ipaddr":"172.16.11.129",
"hostname":"TMC-R.PRM01",
"posisi":"6",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}{
"ch":"113",
"ipaddr":"172.16.11.130",
"hostname":"TMC-R.PRM03",
"posisi":"8",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}{
"ch":"114",
"ipaddr":"172.16.11.131",
"hostname":"TMC-R.PRM02",
"posisi":"7",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}{
"ch":"115",
"ipaddr":"172.16.11.132",
"hostname":"TMC-R.PRM04",
"posisi":"9",
"monitorid":"17",
"view_dimension":"2*2",
"input_ipaddr":""
}';
$render = renderLayout3x3($json_data);
print $render; ?>
总是输出:
Output : "2","1","3","4","5","6","7","8","9"
为什么:2 - 1 - 3 - 等,而不是1 - 2 - 3 - 等
答案 0 :(得分:0)
这是因为如果你的代码中的语句不能决定你输出的顺序是什么。
您可以使用usort重新排列您的$数据,
usort(&$data, function($a, $b){return $a['posisi'] <=> $b['posisi'];});
答案 1 :(得分:0)
您必须对数组进行排序,然后才能获得排序数组列表。你可以使用ksort()函数来对你的数组进行排序
答案 2 :(得分:0)
首先在你的字符串上有一个错误的json格式。 如果您的json格式正确,那么就这样做
public function renderLayout3x3($data=array()){
$data = json_decode($data); // decode json format to array
// set posisi as index
foreach ($data as $key => $value)
{
$data[intval($value['posisi'])] = $value;
}
// sort index
ksort($data);
// get array values to data
$data = array_values($data);
$output = "";
foreach ($data as $key => $value) {
$output .= '<li><ul>
<li>POS:'.$value["posisi"].'</li>
<li>HOSTNAME:'.$value["hostname"].'</li>
</ul></li>';
}
return "<ul>$output</ul>";
}
答案 3 :(得分:0)