php - 如何使用 PHP 将输出数组转换为字符串或变量?
问题描述
我在数组中得到一个输出:
array (size=3)
8 => string 'Mexico' (length=6)
24 => string 'UAE' (length=3)
34 => string 'India' (length=5)
array (size=9)
2 => string '' (length=0)
8 => string 'Large' (length=5)
14 => string '' (length=0)
19 => string '' (length=0)
23 => string '' (length=0)
24 => string 'Micro' (length=5)
34 => string 'Large' (length=5)
35 => string '' (length=0)
38 => string '' (length=0)
我想要以下格式的输出:这意味着需要比较两者的 id。
Mexico - Large (8)
UAE - Micro (24)
India - Large (34)
PHP 脚本
<?php
$entities = $check_list = [];
foreach($_POST as $k => $v) {
if(preg_match("/^check_list(\d+)$/", $k, $matches))
$check_list[intval($matches[0])] = $v;
unset($matches);
if(preg_match("/^entity_selected(\d+)$/", $k, $matches))
$entities[intval($matches[0])] = $v;
};
var_dump($_POST['check_list']);
var_dump($_POST['entity_selected']);
echo implode(" ",$_POST['entity_selected'])."<br>";
echo implode(" ",$_POST['check_list'])."<br>";
?>
我需要比较变量并将数据相应地插入数据库。但我无法将这些数据变成变量。我怎样才能做到这一点?
这是我的 PHP 表单脚本:
<form method="POST" action="nextpage1.php">
<table border="1">
<?php
$i = 0;
while($row1 = mysqli_fetch_array($result_country)) {
$country1 = $row1['country'];
$entity1 = $row1['entity'];
echo "<tr>";
?>
<td>
<input name="check_list[<?php echo $i; ?>]" type="checkbox" value="<?php echo $country1;?>"> <?php echo $country1;?>
</td>
<td>
<?php
if($entity1=="Yes") {
?>
<select class="form-control selectpicker" name="entity_selected[<?php echo $i; ?>]">
<option value="">Select</option>
<option value="Micro">Micro</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
<?php
};
?>
</td>
<?php
$i++;
echo "</tr>";
};
?>
</table>
基本上,表单脚本由一些带有复选框的国家和用于选择实体的下拉菜单组成。因此,无论哪个复选框都选择了该值(国家名称),并且必须捕获实体并将其插入数据库。
解决方案
你把它复杂化了。只需循环$_POST['check_list']
并使用它的键找到相关的值$_POST['entity_selected']
:
foreach ($_POST['check_list'] as $key => $country) {
echo $country . ' - ' . $_POST['entity_selected'][$key] . ' (' . $key . ')'. "\n";
}
这假设在 中总是有一个对应的键。$_POST['entity_selected']
$_POST['check_list']
如果你想让输出在眼睛上更容易一点,你也可以printf()
用来帮助格式化:
foreach ($_POST['check_list'] as $key => $country) {
printf('%s - $s (%u)%s', $country, $_POST['entity_selected'][$key], $key, "\n");
}
推荐阅读
- slack - 每次发布新消息时,是否都会调用监听特定消息事件的 Slack 机器人?有没有人遇到过这个问题?
- javascript - Cloudfront 不断将我重定向到 index.html
- docker - Redis HA 与 Docker 上的 Sentinel
- forms - Symfony 5 如何使用 paramconverter 作为字段之一的值创建表单
- java - 如何对 Lucene 查询搜索结果执行新的查询搜索
- bash - 如何提取没有 zip 文件夹名称的 .zip
- sql - STRING_AGG 替代 SQL Server 2008
- reactjs - 使用 recharts 或 react-chartjs-2 使用 ReactJS 创建混合条形图
- json - 了解 JSON 迭代
- ruby-on-rails - QBXML SalesOrderAdd 问题