如何在PHP中循环遍历JSON嵌套数组值?数据表

时间:2019-01-15 16:42:12

标签: php mysql json datatable

我在mysql中的数据库有一个名为“ sales”的表,其中有一个“ products”字段,其中几个产品在json中“出售”,并且在此json中,我只需要获取信息“ brand”和“ model”将其显示在数据表中,谢谢。

这是我桌子的图像。

enter image description here

Here is the json [{"id":"312","marca":"NIKON","modelo":"D3400","serie":"8857882","cantidad":"1","stock":"0","precio":"1669","total":"1669"},{"id":"161","marca":"NIKON","modelo":"AF-P NIKKOR 18-55MM 1:3.5-5.6G","serie":"21963658","cantidad":"1","stock":"0","precio":"0","total":"0"}]

public function mostrarTablaSell(){
    $item = null;
    $valor = null;
    $orden = "id";

    $ventas = ControladorVentas::ctrMostrarVentas($item, $valor, $orden);   

    if(count($ventas) == 0){
        echo '{"data": []}';
        return;
    }

    $datosJson = '{
                  "data": [';
    for($i = 0; $i < count($ventas); $i++){
        /*=============================================
          PRODUCTOS
          =============================================*/ 
        $here = json_decode($ventas[$i]["productos"], true);

        foreach ($here as $key => $value) {
            $productos1 = $value['marca'];
            $productos2 = $value['modelo'];
        }

        //$productos0 = $here[0]['categoria'];
        //$productos1 = $here[0]['marca'];
        //$productos2 = $here[0]['modelo'];
        $productos = $productos1 .' '. $productos2;

        /*=============================================
          TRAEMOS LAS ACCIONES
          =============================================*/ 
        if(isset($_GET["perfilOculto"]) && $_GET["perfilOculto"] == "Especial"){
            $botones =  "<div class='btn-group'><button class='btn btn-warning btnEditarVenta' idVenta='".$ventas[$i]["id"]."'><i class='fa fa-pencil'></i></button><button class='btn btn-danger btnEliminarVenta' idVenta='".$ventas[$i]["id"]." '><i class='fa fa-times'></i></button><button class='btn btn-info btnImprimirFactura' codigoVenta='".$ventas[$i]["codigo"]."'><i class='fa fa-print'></i></button></div>"; 
        }else{
            $botones =  "<div class='btn-group'><button class='btn btn-warning btnEditarVenta' idVenta='".$ventas[$i]["id"]."'><i class='fa fa-pencil'></i></button><button class='btn btn-danger btnEliminarVenta' idVenta='".$ventas[$i]["id"]." '><i class='fa fa-times'></i></button><button class='btn btn-info btnImprimirFactura' codigoVenta='".$ventas[$i]["codigo"]."'><i class='fa fa-print'></i></button></div>"; 
        }

        $datosJson .='[
                              "'.($i+1).'",
                              "'.$ventas[$i]["id"].'",
                              "'.$ventas[$i]["codigo"].'",
                              "'.$vendedor.'",
                              "'.$cliente.'",
                              "'.$ventas[$i]["proviene"].'",
                              "'.$productos.'",
                              "'.$ventas[$i]["desp"].'",
                               "'.$ventas[$i]["adelanto"].'",
                              "'.$ventas[$i]["total"].'",
                              "'.$ventas[$i]["estado"].'",
                              "'.$ventas[$i]["obs"].'",
                              "'.$ventas[$i]["fecha"].'",
                              "'.$botones.'"
                            ],';
    }
    $datosJson = substr($datosJson, 0, -1);
    $datosJson .=   '] 
                 }';
    echo $datosJson;
}
}

1 个答案:

答案 0 :(得分:0)

我想我了解您的目标。这是一个片段...

代码:(Demo

double dd = 1.1;
int ii = 2;
ii += dd; // this is a possible bug

输出:

$ventas[0]["productos"] = '[{"id":"312","marca":"NIKON","modelo":"D3400","serie":"8857882","cantidad":"1","stock":"0","precio":"1669","total":"1669"},{"id":"161","marca":"NIKON","modelo":"AF-P NIKKOR 18-55MM 1:3.5-5.6G","serie":"21963658","cantidad":"1","stock":"0","precio":"0","total":"0"}]';
// do not write the above sample data in your code.

$data = [];

foreach ($ventas as $row) {
    foreach (json_decode($row["productos"], true) as $details) {
        $data[] = [$details['marca'], $details['modelo']];
    }
}

echo json_encode(['data' => $data]);

使用{"data":[["NIKON","D3400"],["NIKON","AF-P NIKKOR 18-55MM 1:3.5-5.6G"]]} 代替foreach无需使用for并提供更简单的语法。

使用count作为最后一步,使代码更加稳定且易于阅读。

您确实应该对表结构进行规范化以允许更轻松/更好的查询。将其存储为json需要更多的处理,并且会破坏构建聪明/直接查询的机会。