简体   繁体   中英

check the position of values in JSON object array in php

I have a JSON (Line A) as shown below.

   $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'));
    }

    {"toggle_multi_tiles":["0","1"]}  // Line A

What I want is for the,

=> 1st value in JSON object array above at Line A, animation-delay:0s; is applied.

=> 2nd value, animation-delay:4s; is applied.

This is what I have tried:

    <?php
    if($data->toggle_multi_tiles[0]) {                 /* For 1st element */
    ?>
    .multi-tiles a:nth-of-type(1) {
        animation-delay: 0s;
    }

    <?php } ?>

    <?php
    if($data->toggle_multi_tiles[1]) {              /* For 2nd element */
    ?>
    .multi-tiles a:nth-of-type(2) {
        animation-delay: 4s;
    }

    <?php } ?>

Problem Statement:

I have used the if-logic above to apply animation-delay of 0sec onto the 1st value of JSON object array but the if condition will fail there as "0" is false. I am wondering what changes I should make in the php code above so that for

=> 1st value in JSON object array above at Line A, animation-delay:0s; is applied.

=> 2nd value, animation-delay:4s; is applied.

Maybe you should be looping through the array.

foreach ($data->toggle_multi_tiles as $i => $value) {
?>
.multi-tiles a:nth-of-type(<?php echo $i+1; ?>) {
    animation-delay: <?php echo 4 * $value; ?>s;
}

So when the array element is 0 you get 0s , when it's 1 you get 4s , when it's 2 you get 8s , and so on.

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