PHP - JSON Question

Skythrust

Member
Jul 9, 2019
133
7
Hi there,

I would like to have some details from a JSON into a PHP page.

JSON:
[{"Name":"Diesel,Jhon",,"Time":"2021-02-11T09:45:17.517","Online":true},{"Name":"Doe,Jane",,"Time":"2021-02-11T09:47:17.517","Online":false}]

It needs to look like this below, but not hardcoded. And when there is another record it need to come here as well. Other important thing is that the status Online makes the switch between TextOn or TextOff

HTML:
<div class="TextOn">John von Diesel
    <label class="switch">
        <input type="checkbox" checked>
        <span class="slider round"></span>
    </label>
</div>
<div class="TextOff">Jane Doe
    <label class="switch">
        <input type="checkbox" unchecked>
        <span class="slider round"></span>
    </label>
</div>

Any idea how I can realise this?
 
Solution
This is a bit of spoonfeeding, but without enough information. Where is the JSON coming from? Why do you want it to come from JSON? Feels like you're having a school assignment and you're letting someone else do the job. This is really basic PHP. The most basic stuff you can find.

Also, your JSON was invalid.

PHP:
<?php
$json = '[{"Name":"Diesel,Jhon","Time":"2021-02-11T09:45:17.517","Online":true},{"Name":"Doe,Jane","Time":"2021-02-11T09:47:17.517","Online":false}]';
$data = json_decode($json, true);

foreach ($data as $record) {
    ?>
    <div class="<?= $record['Online'] ? 'TextOn' : 'TextOff'; ?>"><?= $record['Name']; ?>
    <label class="switch">
        <input type="checkbox" checked>
        <span class="slider round"></span>...

Weasel

👄 I'd intercept me
Nov 25, 2011
4,135
2,461
This is a bit of spoonfeeding, but without enough information. Where is the JSON coming from? Why do you want it to come from JSON? Feels like you're having a school assignment and you're letting someone else do the job. This is really basic PHP. The most basic stuff you can find.

Also, your JSON was invalid.

PHP:
<?php
$json = '[{"Name":"Diesel,Jhon","Time":"2021-02-11T09:45:17.517","Online":true},{"Name":"Doe,Jane","Time":"2021-02-11T09:47:17.517","Online":false}]';
$data = json_decode($json, true);

foreach ($data as $record) {
    ?>
    <div class="<?= $record['Online'] ? 'TextOn' : 'TextOff'; ?>"><?= $record['Name']; ?>
    <label class="switch">
        <input type="checkbox" checked>
        <span class="slider round"></span>
    </label>
</div>
    <?php
}
?>
 
Last edited:
Solution

Object

?
Nov 10, 2017
429
352
Just to elaborate on the answer above, so that you'll hopefully be able to understand what's going on and in the future can apply such yourself :)

First, a variable "$json" is being assigned to an array with json data.
Secondly, the json data is being decoded and assigned to the "$data" variable.

This returns and array with a new instance the stdClass for each json object

Thirdly the foreach is being used to loop through the array of data and inside the foreach the first div is being used to apply the textOn or the textOff class, which is being achieved by the use of ternary operators

<?= is a shorthand for "<?php echo" then it fetches the online status, the "?" means if true textOn and the ":" is else apply textOff

So:
PHP:
<?= $record['Online'] ? 'TextOn' : 'TextOff'; ?>

Becomes

PHP:
if ($record['Online] == true)  {
    textOn
}  else  {
    textOff
}
 

Skythrust

Member
Jul 9, 2019
133
7
Hi Guys,

The issue is more that I am doing a lot of programming stuff by searching the internet. Not really done an education for that.

The JSON output is from Postman.
 

Skythrust

Member
Jul 9, 2019
133
7
That's totally fine, I hope Wess' post and my explanation, gave it a bit of sense :)
I Already have fix this :) now trying to find a way to cross join JSON strings (2 JSON strings with 1 primary key) and again the echo rows in table shit (4 records per row)

You must be registered for see images attach
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
Just to elaborate on the answer above, so that you'll hopefully be able to understand what's going on and in the future can apply such yourself :)

First, a variable "$json" is being assigned to an array with json data.
Secondly, the json data is being decoded and assigned to the "$data" variable.

This returns and array with a new instance the stdClass for each json object

Thirdly the foreach is being used to loop through the array of data and inside the foreach the first div is being used to apply the textOn or the textOff class, which is being achieved by the use of ternary operators

<?= is a shorthand for "<?php echo" then it fetches the online status, the "?" means if true textOn and the ":" is else apply textOff

So:
PHP:
<?= $record['Online'] ? 'TextOn' : 'TextOff'; ?>

Becomes

PHP:
if ($record['Online] == true)  {
    textOn
}  else  {
    textOff
}
Probably worth bearing in mind however that the <?= shorthand isn’t enabled by default on all hosts, so if problems arise with it, simply switch it to <?php echo and all should be well.

But yeah, good explanation @RushDK and nice example @Wess :)
 

Weasel

👄 I'd intercept me
Nov 25, 2011
4,135
2,461
Probably worth bearing in mind however that the <?= shorthand isn’t enabled by default on all hosts, so if problems arise with it, simply switch it to <?php echo and all should be well.

But yeah, good explanation @RushDK and nice example @Wess :)

That would be really weird, as it's enabled by default in PHP since 5.4 - I see no reason why hosts would switch that off. Aren't you confusing the shorthand <? operator? Because that's been deprecated/removed, but that's different from <?=
 

Skythrust

Member
Jul 9, 2019
133
7
Back again..

I am trying to loop after item, this is working when I am doing it with this code;

PHP:
echo "<td><div class='TextOff'>"

But because the class is changing if the Online value is 0 or 1

so I thaught I need to use this but that isn't working.
PHP:
echo "<td>".
if ($record['Online'] == 1) { "<div class='TextOn'>"; } else { "<div class='TextOff'>"; }

I also have tried this
PHP:
// A
echo "<td><div class=". if ($record['Online'] == 1) {'TextOn'.} else {'TextOff'.} ">"

// B
echo "<td><div class=". if ($record['Online'] == 1) {'TextOn'} else {'TextOff'} . ">"
    
// C (is working but not an if else solution)
echo "<td><div class=". 'TextOn'. ">"

The code for the switch/checkbox is working fine
Full Code;
PHP:
<section>
    <?php
    $i =0;
    echo "<table><tr>";
    foreach($data as $record)
    {
        $i++;
        echo "<td><div class='TextOff'>"
            //                            echo "<td>".
            //                    if ($record['Online'] == 1) { "<div class='TextOn'>"; } else { "<div class='TextOff'>"; }
            .$record['Name']; ?>

            <label class="switch">
            <input type="checkbox" <?php if ($record['Online'] == 1) { echo 'checked'; } else { echo 'unchecked'; } ?>>
                <span class="slider round"></span>
                </label>
                </div>
                <?php
                '</td>';
        $item++;
        if ($item % 2 == 0) { echo '</tr><tr>'; }
    }
?>
    </table>                       
</section>
 

Weasel

👄 I'd intercept me
Nov 25, 2011
4,135
2,461
Back again..

I am trying to loop after item, this is working when I am doing it with this code;

PHP:
echo "<td><div class='TextOff'>"

But because the class is changing if the Online value is 0 or 1

so I thaught I need to use this but that isn't working.
PHP:
echo "<td>".
if ($record['Online'] == 1) { "<div class='TextOn'>"; } else { "<div class='TextOff'>"; }

I also have tried this
PHP:
// A
echo "<td><div class=". if ($record['Online'] == 1) {'TextOn'.} else {'TextOff'.} ">"

// B
echo "<td><div class=". if ($record['Online'] == 1) {'TextOn'} else {'TextOff'} . ">"
   
// C (is working but not an if else solution)
echo "<td><div class=". 'TextOn'. ">"

The code for the switch/checkbox is working fine
Full Code;
PHP:
<section>
    <?php
    $i =0;
    echo "<table><tr>";
    foreach($data as $record)
    {
        $i++;
        echo "<td><div class='TextOff'>"
            //                            echo "<td>".
            //                    if ($record['Online'] == 1) { "<div class='TextOn'>"; } else { "<div class='TextOff'>"; }
            .$record['Name']; ?>

            <label class="switch">
            <input type="checkbox" <?php if ($record['Online'] == 1) { echo 'checked'; } else { echo 'unchecked'; } ?>>
                <span class="slider round"></span>
                </label>
                </div>
                <?php
                '</td>';
        $item++;
        if ($item % 2 == 0) { echo '</tr><tr>'; }
    }
?>
    </table>                      
</section>

This has to do with the fact that an if/else statement doesn't work inside an echo. You can try to use the instead. You can find an example in .
 

Skythrust

Member
Jul 9, 2019
133
7
Thanks @Wess!

What is the best way to filter the JSON Array? On the internet they are talking about filter_array(), but it seems like that is not working for me. For example the Department to show only the persons which are in Dept 3, or the online state is true.

JSON:
$jsonstringDept = '[
            {"DeptId":1,"DepartmentName":"CEO"},
            {"DeptId":2,"DepartmentName":"NASDAQ"},
            {"DeptId":3,"DepartmentName":"Marvel Studios"},
            {"DeptId":4,"DepartmentName":"Lucasfilm"}
        ]';

$jsonstringPerson = '[    
            {"FrstName":"Henry","Middlename":"","LastName":"Walton","Online":true,"DeptId":"4"},
            {"FrstName":"Klaus","Middlename":"","LastName":"Mikaelson","Online":true,"DeptId":"2"},
            {"FrstName":"Kylo","Middlename":"","LastName":"Ren","Online":false,"DeptId":"4"},
            {"FrstName":"Stan","Middlename":"","LastName":"Lee","Online":false,"DeptId":"3"},
            {"FrstName":"Kevin","Middlename":"","LastName":"McNally","Online":false,"DeptId":"3"},
            {"FrstName":"Katherine","Middlename":"","LastName":"Pierce","Online":false,"DeptId":"2"},
            {"FrstName":"Clint","Middlename":"","LastName":"Barton","Online":true,"DeptId":"3"},
            {"FrstName":"Hope","Middlename":"van","LastName":"Dyne","Online":false,"DeptId":"3"}
        ]';

Full Code;
PHP:
<?php
$i =0;
echo "<table><tr>";
foreach($data as $record)
{
    if ($record['APBArea'] == 2) { $APBAreadiv = 'TextOn'; $APBCheck = 'checked'; } else { $APBAreadiv = 'TextOff'; $APBCheck = 'unchecked'; }
    if ($record['Pin'] == 1) { $BHVDiv = 'fas fa-user-plus'; $BHVValue = ' (BHV)'; } else { $BHVDiv = 'fas fa-user'; $BHVValue = ''; }

    $i++;
    echo "<td><div class=".$APBAreadiv."><i class='".$BHVDiv."'></i>"
        .' '.$record['FrstName'] .' '. $record['MiddleName'] .' '. $record['LastName']. $BHVValue;

    echo '<label class="switch">
        <input type="checkbox"'.$APBCheck.'>
        <span class="slider round"></span>
        </label>
    </div>                         
    </td>';
    $i++;
    if ($i % 5 == 0) { echo '</tr><tr>'; }
}                       
echo '</table>';                                 
}

?>
 

Weasel

👄 I'd intercept me
Nov 25, 2011
4,135
2,461
Thanks @Wess!

What is the best way to filter the JSON Array? On the internet they are talking about filter_array(), but it seems like that is not working for me. For example the Department to show only the persons which are in Dept 3, or the online state is true.

JSON:
$jsonstringDept = '[
            {"DeptId":1,"DepartmentName":"CEO"},
            {"DeptId":2,"DepartmentName":"NASDAQ"},
            {"DeptId":3,"DepartmentName":"Marvel Studios"},
            {"DeptId":4,"DepartmentName":"Lucasfilm"}
        ]';

$jsonstringPerson = '[  
            {"FrstName":"Henry","Middlename":"","LastName":"Walton","Online":true,"DeptId":"4"},
            {"FrstName":"Klaus","Middlename":"","LastName":"Mikaelson","Online":true,"DeptId":"2"},
            {"FrstName":"Kylo","Middlename":"","LastName":"Ren","Online":false,"DeptId":"4"},
            {"FrstName":"Stan","Middlename":"","LastName":"Lee","Online":false,"DeptId":"3"},
            {"FrstName":"Kevin","Middlename":"","LastName":"McNally","Online":false,"DeptId":"3"},
            {"FrstName":"Katherine","Middlename":"","LastName":"Pierce","Online":false,"DeptId":"2"},
            {"FrstName":"Clint","Middlename":"","LastName":"Barton","Online":true,"DeptId":"3"},
            {"FrstName":"Hope","Middlename":"van","LastName":"Dyne","Online":false,"DeptId":"3"}
        ]';

Full Code;
PHP:
<?php
$i =0;
echo "<table><tr>";
foreach($data as $record)
{
    if ($record['APBArea'] == 2) { $APBAreadiv = 'TextOn'; $APBCheck = 'checked'; } else { $APBAreadiv = 'TextOff'; $APBCheck = 'unchecked'; }
    if ($record['Pin'] == 1) { $BHVDiv = 'fas fa-user-plus'; $BHVValue = ' (BHV)'; } else { $BHVDiv = 'fas fa-user'; $BHVValue = ''; }

    $i++;
    echo "<td><div class=".$APBAreadiv."><i class='".$BHVDiv."'></i>"
        .' '.$record['FrstName'] .' '. $record['MiddleName'] .' '. $record['LastName']. $BHVValue;

    echo '<label class="switch">
        <input type="checkbox"'.$APBCheck.'>
        <span class="slider round"></span>
        </label>
    </div>                       
    </td>';
    $i++;
    if ($i % 5 == 0) { echo '</tr><tr>'; }
}                     
echo '</table>';                               
}

?>

Here's an example of how to use the array_filter function. As I don't see an array filter in your example, not sure what you did wrong. Next time, please include it in the thread, otherwise, I can't teach you. The below example has 2 ways of doing it, depending on your PHP version.

PHP:
<?php

$jsonstringPerson = '[  
    {"FrstName":"Henry","Middlename":"","LastName":"Walton","Online":true,"DeptId":"4"},
    {"FrstName":"Klaus","Middlename":"","LastName":"Mikaelson","Online":true,"DeptId":"2"},
    {"FrstName":"Kylo","Middlename":"","LastName":"Ren","Online":false,"DeptId":"4"},
    {"FrstName":"Stan","Middlename":"","LastName":"Lee","Online":false,"DeptId":"3"},
    {"FrstName":"Kevin","Middlename":"","LastName":"McNally","Online":false,"DeptId":"3"},
    {"FrstName":"Katherine","Middlename":"","LastName":"Pierce","Online":false,"DeptId":"2"},
    {"FrstName":"Clint","Middlename":"","LastName":"Barton","Online":true,"DeptId":"3"},
    {"FrstName":"Hope","Middlename":"van","LastName":"Dyne","Online":false,"DeptId":"3"}
]';

$persons = json_decode($jsonstringPerson, true);

// With the shorthand "Arrow" Function (fn) - from PHP7.4 and higher
$filtered = array_filter($persons, fn($person) => $person['DeptId'] === "3" || $person['Online'] === true);

// With an anonymous function (PHP7.3 and lower)
$filtered = array_filter($persons, function($person) {
    return $person['DeptId'] === "3" || $person['Online'] === true;
});

Which, in both examples will output:

Code:
array(6) {
  [0]=>
  array(5) {
    ["FrstName"]=>
    string(5) "Henry"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(6) "Walton"
    ["Online"]=>
    bool(true)
    ["DeptId"]=>
    string(1) "4"
  }
  [1]=>
  array(5) {
    ["FrstName"]=>
    string(5) "Klaus"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(9) "Mikaelson"
    ["Online"]=>
    bool(true)
    ["DeptId"]=>
    string(1) "2"
  }
  [3]=>
  array(5) {
    ["FrstName"]=>
    string(4) "Stan"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(3) "Lee"
    ["Online"]=>
    bool(false)
    ["DeptId"]=>
    string(1) "3"
  }
  [4]=>
  array(5) {
    ["FrstName"]=>
    string(5) "Kevin"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(7) "McNally"
    ["Online"]=>
    bool(false)
    ["DeptId"]=>
    string(1) "3"
  }
  [6]=>
  array(5) {
    ["FrstName"]=>
    string(5) "Clint"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(6) "Barton"
    ["Online"]=>
    bool(true)
    ["DeptId"]=>
    string(1) "3"
  }
  [7]=>
  array(5) {
    ["FrstName"]=>
    string(4) "Hope"
    ["Middlename"]=>
    string(3) "van"
    ["LastName"]=>
    string(4) "Dyne"
    ["Online"]=>
    bool(false)
    ["DeptId"]=>
    string(1) "3"
  }
}
array(6) {
  [0]=>
  array(5) {
    ["FrstName"]=>
    string(5) "Henry"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(6) "Walton"
    ["Online"]=>
    bool(true)
    ["DeptId"]=>
    string(1) "4"
  }
  [1]=>
  array(5) {
    ["FrstName"]=>
    string(5) "Klaus"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(9) "Mikaelson"
    ["Online"]=>
    bool(true)
    ["DeptId"]=>
    string(1) "2"
  }
  [3]=>
  array(5) {
    ["FrstName"]=>
    string(4) "Stan"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(3) "Lee"
    ["Online"]=>
    bool(false)
    ["DeptId"]=>
    string(1) "3"
  }
  [4]=>
  array(5) {
    ["FrstName"]=>
    string(5) "Kevin"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(7) "McNally"
    ["Online"]=>
    bool(false)
    ["DeptId"]=>
    string(1) "3"
  }
  [6]=>
  array(5) {
    ["FrstName"]=>
    string(5) "Clint"
    ["Middlename"]=>
    string(0) ""
    ["LastName"]=>
    string(6) "Barton"
    ["Online"]=>
    bool(true)
    ["DeptId"]=>
    string(1) "3"
  }
  [7]=>
  array(5) {
    ["FrstName"]=>
    string(4) "Hope"
    ["Middlename"]=>
    string(3) "van"
    ["LastName"]=>
    string(4) "Dyne"
    ["Online"]=>
    bool(false)
    ["DeptId"]=>
    string(1) "3"
  }
}
 

Skythrust

Member
Jul 9, 2019
133
7
That is awesome Wess!

Everything is working fine over here, now I am going to the next chapter the div needs to be responsive. on every screen format it needs to work perfect. And if the div is full of blocks that it starts a virtual page which will switch per page every x seconds.
In the spoilers below 3 screenshots the Windows Screen is the one which is okay.

The text inside the blocks is blurred because of the privacy.

You must be registered for see images attach

You must be registered for see images attach

You must be registered for see images attach
 

Weasel

👄 I'd intercept me
Nov 25, 2011
4,135
2,461
That is awesome Wess!

Everything is working fine over here, now I am going to the next chapter the div needs to be responsive. on every screen format it needs to work perfect. And if the div is full of blocks that it starts a virtual page which will switch per page every x seconds.
In the spoilers below 3 screenshots the Windows Screen is the one which is okay.

The text inside the blocks is blurred because of the privacy.

You must be registered for see images attach

You must be registered for see images attach

You must be registered for see images attach

I would recommend you to make a new thread for this, include your CSS/HTML and what you've tried. But I would advise you to have a look at the @media queries in CSS.


W3schools isn't the best, but it gives a proper view. With this, you can change the CSS based on screen width.
 

Users who are viewing this thread

Top