Skip to content

Instantly share code, notes, and snippets.

@phpfiddle
Created February 4, 2020 01:54
Show Gist options
  • Save phpfiddle/98123a25008cd7e2e210600ab7224b83 to your computer and use it in GitHub Desktop.
Save phpfiddle/98123a25008cd7e2e210600ab7224b83 to your computer and use it in GitHub Desktop.
[ Posted by Victor Lopez ] Ejemplo json encode decode
<?php
$vjson = '[{"id":1,"proyecto":"01","ncosto":"112000000.00","unidades_rh":33792}, {"id":2,"proyecto":"02","ncosto":"5000000.00","unidades_rh":256000}, {"id":3,"proyecto":"03","ncosto":"70000000.00","unidades_rh":11088}, {"id":4,"proyecto":"04","ncosto":"300000000.00","unidades_rh":6336}, {"id":5,"proyecto":"05","ncosto":"10000000.00","unidades_rh":5280}]';
$arr1 = json_decode($vjson,true);
print_r($arr1);
echo "<br><br>";
$totCosto = $totRH = 0;
$totRecs = count($arr1);
$txtArray = 'array("total"=>'.$totRecs.', "rows"=> array( ';
foreach ($arr1 as $fila => $valor) {
$cid = $valor['id'];
$cproy = $valor['proyecto'];
$costo = $valor['ncosto'];
$urh = $valor['unidades_rh'];
$totCosto += $costo;
$totRH += $urh;
$txtArray .= 'array("id"=>'. $cid .', "proyecto"=>"'. $cproy .'", "ncosto"=>'.$costo.', "unidades_rh"=>'.$urh.'), ';
}
$txtFooter = '), "footer"=>array( ';
$txtFooter .= 'array("ntotpuntos"=>"TOTAL", "ncosto"=>'.$totCosto.', "unidades_rh"=>'.$totRH.'), ';
$txtFooter .= 'array("ntotpuntos"=>"RESTRICCION", "ncosto"=>500000000, "unidades_rh"=>80008000),));';
$txtArray .= $txtFooter;
echo "NUEVO JSON <br><br>";
$arrFinal = 'txtArray';
$arrFinal = json_encode($$arrFinal);
print_r($arrFinal);
?>
@rauljrz
Copy link

rauljrz commented Feb 4, 2020

ARRAY INCOMPLETO
"; print_r($arr1); echo "

"; $totCosto= $totRH = 0; $totRecs = count($arr1); foreach ($arr1 as $fila => $valor) { $totCosto += $valor ["ncosto"]; $totRH += $valor ["unidades_rh"]; } $laFooter[0]=array("ntotpuntos"=>"TOTAL", "ncosto"=>$totCosto, "unidades_rh"=>$totRH); $laFooter[1]=array("ntotpuntos"=>"RESTRICCION", "ncosto"=>500000000, "unidades_rh"=>80008000); $laReturn["total" ]= $totRecs; $laReturn["rows" ]= $arr1; $laReturn["footer"]= $laFooter; $lcJson = json_encode($laReturn); print_r($lcJson); die(); ?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment