简体   繁体   中英

How to read multiple values from JSON object array in php?

<?php      
    $output['toggle_multi_tiles']=$_POST['toggle_multi_tiles'];  

    $fp = fopen('../feeds/ptp-ess_landing.json', 'w');
    fwrite($fp, json_encode($output));
    fclose($fp);
    logActivity();

    if(file_exists('../feeds/ptp-ess_landing.json')){
    $data = json_decode(file_get_contents('../feeds/ptp-ess_landing.json'));
    }
?>

I have a JSON as shown below:

{"toggle_multi_tiles":["0","1","2","3"]}


What I want is from the php code below I want it to print as:

<p>Hello World<p>
<p>Logical World<p>
<p>Good Morning </p>
<p>Good Evening</p>

It should not print <p>Good Day</p>

Php code:

<?php if ($data->{"toggle_multi_status"} == 1) {
    if(in_array("0", $data->toggle_multi_tiles)) { ?>     
        <p>Hello World<p>
    <?php } else if (in_array("1", $data->toggle_multi_tiles)) { ?>
        <p>Logical World<p>
    <?php } else if(in_array("2", $data->toggle_multi_tiles)) { ?>
        <p> Good Morning </p>
    <?php } else if(in_array("3", $data->toggle_multi_tiles)) { ?>
        <p>Good Evening</p>
    <?php }
    <?php } else if(in_array("4", $data->toggle_multi_tiles)) { ?>
        <p>Good Day</p>
    <?php }
}
?>

$data->toggle_multi_tiles is reading from JSON.

Why not just build an output array with keys that match the numbers in the response that you want to check:

$data   = json_decode(file_get_contents('../feeds/ptp-ess_landing.json'));
$output = ['Hello World','Logical World','Good Morning','Good Evening','Good Day'];

foreach($data->toggle_multi_tiles as $value) {
    echo isset($output[$value]) ? "<p>{$output[$value]}</p>" : "";
}

In this example $output starts at 0 , to use different numbers:

$output = [2=>'Hello World',
           4=>'Logical World',
           6=>'Good Morning',
           8=>'Good Evening','Good Day'];  //etc...

If you want to do totally different things then you can use a switch in the loop, either using the $output or not :

foreach($data->toggle_multi_tiles as $value) {
    switch($value) {
        case 0:
            //complex HTML
            break;
        case 1:
            //complex HTML
            break;
        case 2:
            //complex HTML
            break;
        case 3:
            //complex HTML
            break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM