我需要在特定键的JSON对象中找到2个变量的最小值,并用该值减去所有键。请关注以下JSON数据
$print = '{"Table":[
{"Column":2,"Length":1,"Number":"A4","Row":12,"zindex":0},
{"Column":2,"Length":1,"Number":"A3","Row":11,"zindex":0},
{"Column":2,"Length":1,"Number":"A2","Row":9,"zindex":1},
{"Column":2,"Length":1,"Number":"A1","Row":8,"zindex":1},
{"Column":3,"Length":1,"Number":"B4","Row":12,"zindex":0},
{"Column":3,"Length":1,"Number":"B3","Row":11,"zindex":0},
{"Column":3,"Length":1,"Number":"B2","Row":9,"zindex":0},
{"Column":3,"Length":1,"Number":"B1","Row":8,"zindex":0},
{"Column":4,"Length":1,"Number":"C4","Row":12,"zindex":0},
{"Column":4,"Length":1,"Number":"C3","Row":11,"zindex":0},
{"Column":4,"Length":1,"Number":"C2","Row":9,"zindex":0},
{"Column":4,"Length":1,"Number":"C1","Row":8,"zindex":0}],"ResponseStatus":200,"Message":null}';
我想要上面给出的JSON数据。
$print = '{"Table":[
{"Column":2,"Length":1,"Number":"A4","Row":1,"zindex":0},
{"Column":2,"Length":1,"Number":"A3","Row":0,"zindex":0},
{"Column":2,"Length":1,"Number":"A2","Row":1,"zindex":1},
{"Column":2,"Length":1,"Number":"A1","Row":0,"zindex":1},
{"Column":3,"Length":1,"Number":"B4","Row":1,"zindex":0},
{"Column":3,"Length":1,"Number":"B3","Row":0,"zindex":0},
{"Column":3,"Length":1,"Number":"B2","Row":1,"zindex":1},
{"Column":3,"Length":1,"Number":"B1","Row":0,"zindex":1},
{"Column":4,"Length":1,"Number":"C4","Row":1,"zindex":0},
{"Column":4,"Length":1,"Number":"C3","Row":0,"zindex":0},
{"Column":4,"Length":1,"Number":"C2","Row":1,"zindex":1},
{"Column":4,"Length":1,"Number":"C1","Row":0,,"zindex":1}],"ResponseStatus":200,"Message":null}';
在上面的JSON数据中,请查看Row和zindex。 zindex有两个值" 0和1",这里我希望php代码分别找到zindex 0的最小值,并单独减去zindex 0的剩余值,与zindex 1相同。
我有一个PHP代码,它找到了行的最小值,并用该值减去了剩余的行。但我不知道如何分别为不同的zindexs做这件事。
$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
请帮助我在PHP中解决这个问题。
答案 0 :(得分:0)
尝试将第一个foreach
替换为:
foreach($print['Table'] as $val) {
if (!isset($rows[$val['zindex']])) {
$rows[$val['zindex']] = array();
}
$rows[$val['zindex']][] = $val['Row'];
}
该数组不是具有值的一维数组,而是二维的,具有zindex的每个值的所有Row值。
然后,$least
也应该是一个数组:
$least = array();
foreach ($rows as $zindex = $row) {
$least[$zindex] = min($row);
}
这将分别计算每个zindex值的最小值。
最后,最后foreach
也应该区分zindex
:
foreach ($print['Table'] as &$val) {
$val['Row'] -= $least[$val['zindex']];
}
成功!