我需要在特定键的JSON对象中找到最小值,并用该值减去所有键。
$print = '{"Table":[
{"Column":2,"Length":1,"Number":"A4","Row":12},
{"Column":2,"Length":1,"Number":"A3","Row":11},
{"Column":2,"Length":1,"Number":"A2","Row":9},
{"Column":2,"Length":1,"Number":"A1","Row":8},
{"Column":3,"Length":1,"Number":"B4","Row":12},
{"Column":3,"Length":1,"Number":"B3","Row":11},
{"Column":3,"Length":1,"Number":"B2","Row":9},
{"Column":3,"Length":1,"Number":"B1","Row":8},
{"Column":4,"Length":1,"Number":"C4","Row":12},
{"Column":4,"Length":1,"Number":"C3","Row":11},
{"Column":4,"Length":1,"Number":"C2","Row":9},
{"Column":4,"Length":1,"Number":"C1","Row":8}],"ResponseStatus":200,"Message":null}';
在上面的JSON数据中,我想获得" Row"的最小值,例如,以上JSON数据的最小值ROW是" 8"并且我想用这个最小值减去剩余的ROW。因此,我将获得下面给出的JSON数据。
$print = '{"Table":[
{"Column":2,"Length":1,"Number":"A4","Row":4},
{"Column":2,"Length":1,"Number":"A3","Row":3},
{"Column":2,"Length":1,"Number":"A2","Row":1},
{"Column":2,"Length":1,"Number":"A1","Row":0},
{"Column":3,"Length":1,"Number":"B4","Row":4},
{"Column":3,"Length":1,"Number":"B3","Row":3},
{"Column":3,"Length":1,"Number":"B2","Row":1},
{"Column":3,"Length":1,"Number":"B1","Row":0},
{"Column":4,"Length":1,"Number":"C4","Row":4},
{"Column":4,"Length":1,"Number":"C3","Row":3},
{"Column":4,"Length":1,"Number":"C2","Row":1},
{"Column":4,"Length":1,"Number":"C1","Row":0}],"ResponseStatus":200,"Message":null}';
答案 0 :(得分:0)
获取所有行,然后只使用min()
函数。然后在获得之后,再次循环并使用引用&
进行减法,然后重新编码。粗略的例子:
$rows = array();
$print = json_decode($print, true); // decode
foreach($print['Table'] as $val) { $rows[] = $val['Row']; }
$least = min($rows); // get least // $least = min(array_column($print['Table'], 'Row'));
foreach($print['Table'] as &$val) {
$val['Row'] -= $least; // make subtractions
}
$print = json_encode($print); // re encode
答案 1 :(得分:0)
如果您使用PHP> = 5.5.0:
,请使用此代码 <?php
$print = '{"Table":[
{"Column":2,"Length":1,"Number":"A4","Row":12},
{"Column":2,"Length":1,"Number":"A3","Row":11},
{"Column":2,"Length":1,"Number":"A2","Row":9},
{"Column":2,"Length":1,"Number":"A1","Row":8},
{"Column":3,"Length":1,"Number":"B4","Row":12},
{"Column":3,"Length":1,"Number":"B3","Row":11},
{"Column":3,"Length":1,"Number":"B2","Row":9},
{"Column":3,"Length":1,"Number":"B1","Row":8},
{"Column":4,"Length":1,"Number":"C4","Row":12},
{"Column":4,"Length":1,"Number":"C3","Row":11},
{"Column":4,"Length":1,"Number":"C2","Row":9},
{"Column":4,"Length":1,"Number":"C1","Row":8}],"ResponseStatus":200,"Message":null}';
$obj = json_decode($print, true);
$min = min(array_column($obj['Table'], 'Row'));
foreach($obj['Table'] as $key => $value) {
$obj['Table'][$key]['Row'] -= $min;
}
$out = json_encode($obj);
echo $out;
?>