У меня есть массив данных, который я преобразовал в json, разделив ключи, используемые для каждого цикла.
Данные:
$data = Array
(
[table6-ios-camt] =>
[table6-ios-iamt] =>
[table6-ios-samt] =>
[table6-ios-type] =>
[table6-isd-camt] => 0
[table6-isd-iamt] => 0
[table6-isd-samt] => 0
[table6-isd-type] =>
[table6-ios-csamt] =>
[table6-isd-csamt] => 0
[table6-other-camt] =>
[table6-other-iamt] =>
[table6-other-samt] =>
[table6-other-type] =>
[table6-tran1-camt] => 0
[table6-tran1-iamt] =>
[table6-tran1-samt] => 0
[table6-tran1-type] =>
[table6-tran2-camt] => 0
[table6-tran2-iamt] =>
[table6-tran2-samt] => 0
[table6-tran2-type] =>
[table6-itc_3b-csamt] => 0
[table6-dump_iog-camt] =>
[table6-dump_iog-iamt] =>
[table6-dump_iog-samt] =>
[table6-dump_iog-type] =>
[table6-dump_oth-camt] => 4386.09
[table6-dump_oth-iamt] =>
[table6-dump_oth-samt] => 4386.09
[table6-dump_oth-type] =>
[table6-itc_clmd-camt] =>
[table6-itc_clmd-iamt] =>
[table6-itc_clmd-samt] =>
[table6-itc_clmd-type] =>
[table6-total_10-camt] => 4386.09
[table6-total_10-iamt] => 0
[table6-total_10-samt] => 4386.09
[table6-total_10-type] =>
[table6-total_11-type] =>
[table6-total_8-csamt] => 0
[table6-total_9-csamt] => 0
[table6-dump_iog-csamt] =>
[table6-dump_isrc-camt] =>
[table6-dump_isrc-iamt] =>
[table6-dump_isrc-samt] =>
[table6-dump_isrc-type] =>
[table6-dump_oth-csamt] =>
[table6-iog_goods-camt] =>
[table6-iog_goods-iamt] =>
[table6-iog_goods-samt] =>
[table6-iog_goods-type] => Capital Goods
[table6-itc_clmd-csamt] =>
[table6-total_10-csamt] => 0
[table6-dump_isrc-csamt] =>
[table6-iog_goods-csamt] =>
[table6-iog_inputs-camt] =>
[table6-iog_inputs-iamt] =>
[table6-iog_inputs-samt] =>
[table6-iog_inputs-type] => Input Services
[table6-iog_inputs-csamt] =>
[table6-iog_services-camt] =>
[table6-iog_services-iamt] =>
[table6-iog_services-samt] =>
[table6-iog_services-type] => Input Services
[table6-supp_non_rchrg_goods-camt] =>
[table6-supp_non_rchrg_goods-iamt] =>
[table6-supp_non_rchrg_goods-samt] =>
[table6-supp_non_rchrg_goods-type] => Capital Goods
[table6-supp_rchrg_reg_goods-camt] =>
[table6-supp_rchrg_reg_goods-iamt] =>
[table6-supp_rchrg_reg_goods-samt] =>
[table6-supp_rchrg_reg_goods-type] => Capital Goods
[table6-supp_non_rchrg_goods-csamt] =>
[table6-supp_non_rchrg_inputs-camt] => 4386.09
[table6-supp_non_rchrg_inputs-iamt] =>
[table6-supp_non_rchrg_inputs-samt] => 4386.09
[table6-supp_non_rchrg_inputs-type] => Inputs
[table6-supp_rchrg_reg_goods-csamt] =>
[table6-supp_rchrg_reg_inputs-camt] =>
[table6-supp_rchrg_reg_inputs-iamt] =>
[table6-supp_rchrg_reg_inputs-samt] =>
[table6-supp_rchrg_reg_inputs-type] => Input Services
[table6-supp_non_rchrg_inputs-csamt] =>
[table6-supp_rchrg_reg_inputs-csamt] =>
[table6-supp_rchrg_unreg_goods-camt] =>
[table6-supp_rchrg_unreg_goods-iamt] =>
[table6-supp_rchrg_unreg_goods-samt] =>
[table6-supp_rchrg_unreg_goods-type] => Capital Goods
[table6-supp_non_rchrg_services-camt] =>
[table6-supp_non_rchrg_services-iamt] =>
[table6-supp_non_rchrg_services-samt] =>
[table6-supp_non_rchrg_services-type] => Input Services
[table6-supp_rchrg_reg_services-camt] =>
[table6-supp_rchrg_reg_services-iamt] =>
[table6-supp_rchrg_reg_services-samt] =>
[table6-supp_rchrg_reg_services-type] => Input Services
[table6-supp_rchrg_unreg_goods-csamt] =>
[table6-supp_rchrg_unreg_inputs-camt] =>
[table6-supp_rchrg_unreg_inputs-iamt] =>
[table6-supp_rchrg_unreg_inputs-samt] =>
[table6-supp_rchrg_unreg_inputs-type] => Input Services
[table6-supp_non_rchrg_services-csamt] =>
[table6-supp_rchrg_reg_services-csamt] =>
[table6-supp_rchrg_unreg_inputs-csamt] =>
[table6-supp_rchrg_unreg_services-camt] =>
[table6-supp_rchrg_unreg_services-iamt] =>
[table6-supp_rchrg_unreg_services-samt] =>
[table6-supp_rchrg_unreg_services-type] => Input Services
[table6-supp_rchrg_unreg_services-csamt] =>
);
json:
{
"table6":{
"ios":{
"camt":0,
"iamt":0,
"samt":0,
"csamt":0
},
"isd":{
"camt":0,
"iamt":0,
"samt":0,
"csamt":0
},
"other":{
"camt":0,
"iamt":0,
"samt":0,
"csamt":0
},
"tran1":{
"camt":0,
"iamt":0,
"samt":0,
"csamt":0
},
"tran2":{
"camt":0,
"iamt":0,
"samt":0,
"csamt":0
},
"itc":{
"camt":0,
"iamt":550,
"samt":230,
"csamt":680
},
"iog":[
{
"itc_typ":"cg",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
},
{
"itc_typ":"ip",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
},
{
"itc_typ":"is",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
}
],
"supp_non_rchrg":[
{
"itc_typ":"cg",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
},
{
"itc_typ":"ip",
"camt":4386.09,
"samt":4386.09,
"iamt":0,
"csamt":0
},
{
"itc_typ":"is",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
}
],
"supp_rchrg_reg":[
{
"itc_typ":"cg",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
},
{
"itc_typ":"ip",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
},
{
"itc_typ":"is",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
}
],
"supp_rchrg_unreg":[
{
"itc_typ":"cg",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
},
{
"itc_typ":"ip",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
},
{
"itc_typ":"is",
"camt":0,
"samt":0,
"iamt":0,
"csamt":0
}
]
}
}
Следующее, что я хочу сделать, это сбросить ключи или целые внутренние объекты json.
Keeping in mind the following conditions:
1.If all the keys in the objects are 0 then the entire object will be removed (easy part).
2.If a key in the object has any value other than 0 , the object should not be removed and the key with "0" value should also be there.
я пробовал разделить значение и использовать условия для проверки 0 или нулевых значений, но проблема в том, что он удаляет все ключи, которые имеют 0 значений, таким образом, не выполняя условие 2 для кода.
$vars = $data;
$count = "";
$finalArray = array();
foreach ($vars as $keys => $values) {
foreach ($values as $k => $v) {
foreach ($v as $ke => $ve) {
if ($keys == "table6") {
$count = (array)$v;
foreach ($count as $ck => $cv) {
if ($cv != "0")
{
$flag = true;
break;
}
}
if ($flag == false)
{
array_push($finalArray, $count);
}
}
}
}
print_r($finalArray);
die();
Я ожидал, что вывод будет содержать объекты с парами ключ-значение, которые не содержат 0 значений, но здесь все печатается.
Я думаю, проблема в том, что вы пытаетесь одинаково работать со значениями на разных уровнях, ios
имеет набор числовых значений и поэтому должен обрабатываться напрямую, но iog
и т. д. имеет вложенный набор массивов. Я заметил, что в вашем внутреннем массиве вы, кажется, проверяете данные из одного из циклов более высокого уровня, а не из текущего...
foreach ($v as $ke => $ve) {
if ($keys == "table6") {
$count = (array)$v;
Ваше значение цикла равно $ve
, и все же вы проверяете $v
.
Хотя это, вероятно, не так элегантно, как могло бы быть, чтобы справиться с этим, в основном он найдет все соответствующие элементы, которые необходимо проверить, и использует array_sum()
для сложения всех значений, если результат> 0, тогда он копирует данные (с соответствующей структурой) через...
$vars = $data;
$finalArray = array();
foreach ($vars as $keys => $values) {
foreach ($values as $k => $v) {
// Check if this also has sub-arrays
if ( is_array($v[array_keys($v)[0]] )) {
foreach ($v as $k1 => $v1) {
if ( array_sum($v1) > 0 ) {
$finalArray[$keys][$k][$k1] = $v1;
}
}
}
if ( array_sum($v) > 0 ) {
$finalArray[$keys][$k] = $v;
}
}
}
print_r($finalArray);
Я думаю, что рекурсивный подход здесь лучше - как:
function removeAllZero(&$arr) {
foreach($arr as $k => &$e) {
if (is_array($e) && removeAllZero($e)) // if array goes and all zero
unset($arr[$k]); // remove it
else if ($e != 0) return false; // there are non-zero
}
return true;
}
Обратите внимание на &
, чтобы изменить исходный массив
Живой пример 3х4л
Спасибо за информацию. Ваш подход очень полезен, но по какой-то странной причине он не работает с динамическими наборами данных (думаю, у меня проблемы с манипулированием json, вот почему! но со статическими данными это довольно круто. спасибо
Ваш подход работает как шарм! спасибо за вклад и понимание! я никогда не рассматривал возможность использования array_sum(); сначала я пытался использовать цикл for и увеличивал счетчик, чтобы добиться того же, но не удалось. Спасибо :)