0

I created several views in the JSON array but my JSON displays empty data on PHP

This is my code in PHP:

<?php 

include 'koneksi.php';

$data = $koneksi -> query("SELECT * FROM pricelist");

$results = array();
while($line = mysqli_fetch_object($data))

{
    $results[]=$line;
}
echo json_encode($results);

 ?>

This is the result:

{
        "kategori": "Data 1",
        "id": "4",
        "nama": "Service One",
        "harga": "250000",
        "nama1": "Service Two",
        "harga1": "30000",
        "nama2": "Service Three",
        "harga2": "400000"
    },
    {
        "kategori": "Kapasitor Indoor",
        "id": "5",
        "nama": "",
        "harga": "200000",
        "nama1": "",
        "harga1": "",
        "nama2": "",
        "harga2": ""
    },
    {
        "kategori": "Kapasitor OutDoor",
        "id": "6",
        "nama": "",
        "harga": "300000",
        "nama1": "",
        "harga1": "",
        "nama2": "",
        "harga2": ""

How to hide the value in the nama1 and harga1, because the value is empty.

Thanks.

Mostafa Arian Nejad
  • 1,278
  • 1
  • 19
  • 32

2 Answers2

1

As Lawrence mentioned, extend your query with the columns you actually want to display:

$data = $koneksi -> query("SELECT kategori,id,nama,harga,nama2,harga2 FROM pricelist");
Edwin Krause
  • 1,766
  • 1
  • 16
  • 33
  • if I use this command. in the Kategori : Data 1 name1 and price1 will also not be visible? – Chiko Frainstact Nov 09 '18 at 09:17
  • Your question didn't specify that you want to select only columns with value initially. So this answer is invalid. You should checkout the link posted by @sfili_81 – Edwin Krause Nov 09 '18 at 09:42
0

So long as you don't have any 0 values that you need to preserve, you can use array_filter()'s default/greedy behavior.

while ($row = $data->fetch_assoc()) {  // maintain OO syntax
    $results[] = array_filter($row);   // this removes: empty/falsey values including zero
}
echo json_encode($results);

If you might need to preserver 0 values, while removing empty and null values, then tell array_filter() to use strlen(). (Demo)

while ($row = $data->fetch_assoc()) {           // maintain OO syntax
    $results[] = array_filter($row, 'strlen');  // only removes: false, null, and empty strings
}
echo json_encode($results);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • Even better, you can use array map `$filteredResults = array_map('array_filter', $results)); echo json_encode($filteredResults);` – Damian Dziaduch Nov 09 '18 at 11:26
  • That styling is not without risk. https://3v4l.org/0Tn1m But so long as you check it for a false result value first, that is fine. It's potato vs potatoe really. Regardless of the technique, you have to iterate every value to check it. I guess I could have written out half-a-dozen more different ways, but I feel that would be overkill. – mickmackusa Nov 09 '18 at 11:39