gpt4 book ai didi

PHP 将一个变量的值拆分为多个变量

转载 作者:行者123 更新时间:2023-11-28 23:30:16 25 4
gpt4 key购买 nike


我有一个来自 mysql 的值,我想将其拆分为一个表单中的多个输入字段。

// This is the value from mysql...
$value = "10 - Coles, 15 - Aldi, 5 - Target, 7.77 - Kmart";

// This is how I want to split it....
$amt_1 = "10";
$desc_1 = "Coles";
$amt_2 = "15";
$desc_2 = "Aldi";
$amt_3 = "5";
$desc_3 = "Target";
$amt_4 = "7.77";
$desc_4 = "Kmart";


//So that it can be displayed in input boxes...
<input type="text" value="<?php echo $amt_1; ?>" />
<input type="text" value="<?php echo $desc_1; ?>" />

<input type="text" value="<?php echo $amt_2; ?>" />
<input type="text" value="<?php echo $desc_2; ?>" />

<input type="text" value="<?php echo $amt_3; ?>" />
<input type="text" value="<?php echo $desc_3; ?>" />

<input type="text" value="<?php echo $amt_4; ?>" />
<input type="text" value="<?php echo $desc_4; ?>" />

Now, there is a condition.

$value 可以是空的,也可以是不足以拆分成 4 个部分,这意味着它可以是 $value = "10 - Coles, 15 - Aldi"; 以适应 $amt_1, $desc_1$amt_2, $desc_2。或任何一组 1、2、3 或 4 次拆分。

最佳答案

如果您只需要 4 对,这是我的方法:

$value = "10 - Coles, 15 - Aldi, 5 - Target, 7.77 - Kmart";

$valArr = explode(', ', $value);

for ($i=0; $i<4; $i++) {
if(isset($valArr[$i])) {
$currentVal = explode(' - ',$valArr[$i]);
echo '<input type="text" name="amt_'.($i+1).'" value="'.$currentVal[0].'" />';
echo '<input type="text" name="desc_'.($i+1).'" value="'.$currentVal[1].'" />';
} else {
echo '<input type="text" name="amt_'.($i+1).'" value="NO VALUE" />';
echo '<input type="text" name="desc_'.($i+1).'" value="NO VALUE" />';
}
}

但对我来说更合适的做法是:

$value = "10 - Coles, 15 - Aldi, 5 - Target, 7.77 - Kmart";

$valArr = explode(', ', $value);

foreach ($valArr as $pair) {
$currentVal = explode(' - ',$pair);
echo '<input type="text" name="amt_'.($i+1).'" value="'.$currentVal[0].'" />';
echo '<input type="text" name="desc_'.($i+1).'" value="'.$currentVal[1].'" />';
}

关于PHP 将一个变量的值拆分为多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37559002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com