简体   繁体   English

如何从结构奇怪的PHP数组中回显一个值(该数组的名称可能未知)?

[英]How can I echo a value from an oddly structured PHP array (where the name of the array may not be known)?

I am trying to reference or echo specific values from an array, but i am unclear on the format for how to write the reference to the array. 我正在尝试从数组引用或回显特定的值,但是我不清楚如何将引用写入数组的格式。

I know you can usually echo specific array values using $arrayname[0], etc., but in my example i don't know how to reference the arrayname. 我知道您通常可以使用$ arrayname [0]等来回显特定的数组值,但是在我的示例中,我不知道如何引用arrayname。

<?php for($i = 0; $i <= 1; $i++){ ?>
<select name="paramrow[<?php echo $i; ?>]" onchange="this.form.submit()">
    <option value="-- Select --">-- Select --</option>
    <option value="option1">option 1</option>
    <option value="option2">option 2</option>
    <option value="option3">option 3</option>
</select>
<?php } ?>

this is what shows when I var_dump($_POST);: 这是我var_dump($ _ POST);时显示的内容:

array(1) {
    ["paramrow"]=>
    array(2) {
        [0]=>
        string(12) "-- Select --"
        [1]=>
        string(7) "option2"
    }
}

So in the above, i'd like to know how to reference "option2". 因此,在上面,我想知道如何引用“ option2”。 thanks! 谢谢!

When you use square brackets in an input name, PHP creates an array out of the POST parameters. 在输入名称中使用方括号时,PHP会根据POST参数创建一个数组。 So $_POST['paramrow'] is an array, which you can loop over: 因此$_POST['paramrow']是一个数组,您可以对其进行循环:

foreach ($_POST['paramrow'] as $i => $param) {
    echo "In menu $i you selected $param<br>";
}

or access directly with indexing: 或直接通过索引访问:

echo "The selection from menu #1 is {$_POST['paramrow'][1]}";

 <?php $my_array = ['paramrow' => [ "select", "option2" ] ]; var_dump($my_array); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>StackOverFlow</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"> </script> <script type="text/javascript" src="app.js"></script> </head> <body> <?php foreach ($my_array as $key=>$val) { if( is_array($val) ) { foreach( $val as $k=>$v) { echo "$k = $v"; echo "<br/>"; } } } ?> </body> </html> 

as you can see the structure of the array is like in the code i wrote. 如您所见,数组的结构类似于我编写的代码。 it's an array inside of another array. 它是另一个数组中的一个数组。 so you need to iterate at the first one and the $val is a pointer to the inner array [ "select", "option2" ], so when you iterate with : foreach( $val as $k=>$v) the $v contains the "select" and "option2" respectively. 因此,您需要在第一个迭代, $ val是指向内部数组[“ select”,“ option2”]的指针,所以当您使用以下命令进行迭代时: foreach( $val as $k=>$v) $ v分别包含“选择”和“选项2”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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