如何使用PHP将输出数组转换为字符串或变量?
我在数组中得到一个输出:如何使用PHP将输出数组转换为字符串或变量?,php,arrays,Php,Arrays,我在数组中得到一个输出: 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 '' (
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 SRIPT
<?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>
你把事情复杂化了。只需在$\u POST['check\u list']
中循环,并使用其键在$\u POST['entity\u selected']
中查找关联的值:
foreach ($_POST['check_list'] as $key => $country) {
echo $country . ' - ' . $_POST['entity_selected'][$key] . ' (' . $key . ')'. "\n";
}
这假设在$\u POST['entity\u selected']
中总是有一个对应的键,就像在$\u POST['check\u list']
中一样
如果您想使输出更加直观,还可以使用printf()
帮助设置格式:
foreach ($_POST['check_list'] as $key => $country) {
printf('%s - $s (%u)%s', $country, $_POST['entity_selected'][$key], $key, "\n");
}
以下是我个人对代码美观的看法。我将$key
更改为$id
,然后$size=$\u POST['entity\u selected'][$id]??'大小未知'
thenecho“{$country}-{$size}({$id})”代码>谢谢。@厕所。我已经用表单脚本更新了问题,也是从生成此数组的位置更新的。我在运行第一个脚本时出错。分析错误:语法错误,意外的“$\u POST”(T_变量),应为“,”或“;”我还需要在这里显示实体名称。它没有表现出来是的,我试过了,它现在起作用了。非常感谢。:)有人能帮我吗?