简体   繁体   中英

PHP foreach loop key value error

I want to loop array keys and values for my html form. Array:

Array
(
    [id] => 50e54d84d681c00e603935e3
    [controller] => osmf
    [defaultServiceUrl] => http://media.netd.com.tr
    [serviceUrl] => http://37.48.66.143
    [path] => S1/HLS_VOD/5ea1_1536/index.m3u8?key=49bfee85b05d117a2906368428094e94&app=com.dcom&max=1500
    [preview] => //s.dogannet.tv/q/i/76/1600x900/50e54e8cd681c00e603935e4
)

And here is my PHP code:

<?php
foreach ($json as $key => $value) { 
    ?>
    <input type="hidden" name="<?php $key; ?>" value="<?php echo $value; ?>"></input>
    <?php
    }

But output is:

<input type="hidden" name="" value="50e54d84d681c00e603935e3"></input>

<input type="hidden" name="" value="osmf"></input>

<input type="hidden" name="" value="http://media.netd.com.tr"></input>

<input type="hidden" name="" value="http://37.48.66.141"></input>

<input type="hidden" name="" value="S1/HLS_VOD/5ea1_1536/index.m3u8?key=49bfee85b05d117a2906368428094e94&app=com.dcom&max=1500"></input>

<input type="hidden" name="" value="//s.dogannet.tv/q/i/76/1600x900/50e54e8cd681c00e603935e4"></input>

I can't see name s. On my html form names are empty.

You need to echo the value of $key . By now you are just doing <?php $key; ?> <?php $key; ?> , which does not perform anything. Hence, do:

<?php print $key; ?>"

All together, instead of

<?php
foreach ($json as $key => $value) { 
    ?>
    <input type="hidden" name="<?php $key; ?>" value="<?php echo $value; ?>"></input>
                               ^^^^^^^^^^^^^^
    <?php
    }

Use

<?php
foreach ($json as $key => $value) { 
    ?>
    <input type="hidden" name="<?php echo $key; ?>" value="<?php echo $value; ?>"></input>
                                ^^^^^^^^^^^^^^
    <?php
    }

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