假设有一个输入:
<?php
$all_product = mysqli_query($connect, "SELECT * FROM product WHERE user_id='$fetch_user_id'");
$i= 0;
$m=5;
echo '<table width="100%" margin-left="30px" style="background-color:white;">';
while ($all = mysqli_fetch_array($all_product)) {
if($i%5==0) {
echo "<tr>";
}
echo '<td style="width:20%">';
echo '<img src="'.$all['image'].'" width="150px" height="150px" />
<div class="search_details">
<figcaption>'.$all['name'].'</figcaption>
<figcaption>by '.$all['brand'].'</figcaption><figcaption>₨'.$all['price'].'</figcaption>
<figcaption>Save: ₨'.$local_price.', ('.$all['discount'].'%)</figcaption><figcaption>In stock: '.$all['stock'] .'</figcaption></div>';
echo "</td>";
if($i%$m==$m - 1){
echo "</tr>";
}
$i++;
}
echo "</table>";
?>
我们正试图将其输出为
1,2,C
到目前为止尝试从这里修改: Is there a way to create key-value pairs in Bash script?
KEY=1, VAL1=2, VAL2=C
输出:
for i in 1,2,C ; do KEY=${i%,*,*}; VAL1=${i#*,}; VAL2=${i#*,*,}; echo $KEY" XX "$VAL1 XX "$VAL2"; done
不完全确定上面的磅(“#”)和%是什么意思,使修改变得有点困难。
任何一位大师能开导吗?感谢。
答案 0 :(得分:1)
我通常更喜欢更容易阅读代码,因为bash可以很快变得丑陋。
试试这个:
<强> key_values.sh 强>
#!/bin/bash
IFS=,
count=0
# $* is the expansion of all the params passed in, i.e. $1, $2, $3, ...
for i in $*; do
# '-eq' is checking for equality, i.e. is $count equal to zero.
if [ $count -eq 0 ]; then
echo -n "KEY=$i"
else
echo -n ", VAL${count}=$i"
fi
count=$(( $count + 1 ))
done
echo
示例强>
key_values.sh 1,2,ABC,123,DEF
<强>输出强>
KEY=1, VAL1=2, VAL2=ABC, VAL3=123, VAL4=DEF
答案 1 :(得分:1)
扩大anishsane的评论:
$ echo $1
1,2,3,4,5
$ IFS=, read -ra args <<<"$1" # read into an array
$ out="KEY=${args[0]}"
$ for ((i=1; i < ${#args[@]}; i++)); do out+=", VAL$i=${args[i]}"; done
$ echo "$out"
KEY=1, VAL1=2, VAL2=3, VAL3=4, VAL4=5