Php 每行/使用表行分解和匹配数组
你好,你能给我这个的正确代码吗Php 每行/使用表行分解和匹配数组,php,Php,你好,你能给我这个的正确代码吗 $split_getCreatedfield = explode(",", "3,1,2"); $fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~"); for($row=0;$row<count(fieldsWithValue);$row++){ $data = explode("->", $fieldsWithValue[$row]); } 我宁愿
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
for($row=0;$row<count(fieldsWithValue);$row++){
$data = explode("->", $fieldsWithValue[$row]);
}
我宁愿使用
preg\u match\u all()
,如下所示:
$i = '3,2,1';
$s = '1->Samuel Pulta~2->21~3->Male~';
preg_match_all('/(\d+)->(.*?)(?:~|$)/', $s, $matches);
$fields = array_combine($matches[1], $matches[2]);
foreach (explode(',', $i) as $index) {
if (isset($fields[$index])) {
echo $index, ' = ', $index, ' = ', $fields[$index]. PHP_EOL;
}
}
正则表达式匹配像1->Samuel Pulta
这样的项,并构建一个数组,其中数字作为键,后面的任何内容作为值
然后,您只需迭代必要的索引,并从
$fields
数组中打印相应的值。您的数据采用非常非常规的格式。这样做的目的是什么?我希望$split_getCreatedfield的数量等于$datai我希望一个数组像这样一个数组([0]=>3个男性[1]=>1个Samuel Pulta[2]=>2个21)@Prasanth Bendra不应该使用数组搜索吗$split_getCreatedfield[数组搜索($res[0],$split_getCreatedfield)]。$res[0]。$res[1]@萨缪尔普尔塔:酷,在堆栈溢出中,我们通过投票并接受答案来表示感谢(点击勾号):p我可以在这里插入循环,@萨缪尔普尔塔:编辑了答案,请检查它,请注意td标记=
后的=
符号,如果您不想在答案中添加该符号,请将其删除
<?php
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
$result = array();
foreach($fieldsWithValue as $key => $val){
if(trim($val) != ""){
$res = explode("->",$val);
$res_key = array_search($res[0],$split_getCreatedfield);
$result[$key][] = $split_getCreatedfield[$res_key];
$result[$key][] = $res[0];
$result[$key][] = $res[1];
}
}
krsort($result); /// Not really required
echo "<table>";
foreach($result as $vals){
echo "<tr><td>".$vals[0]."</td><td>=".$vals[1]."</td><td>=".$vals[2]."</td></tr>";
}
echo "</table>";
?>
3 =3 =Male
2 =2 =21
1 =1 =Samuel Pulta
$i = '3,2,1';
$s = '1->Samuel Pulta~2->21~3->Male~';
preg_match_all('/(\d+)->(.*?)(?:~|$)/', $s, $matches);
$fields = array_combine($matches[1], $matches[2]);
foreach (explode(',', $i) as $index) {
if (isset($fields[$index])) {
echo $index, ' = ', $index, ' = ', $fields[$index]. PHP_EOL;
}
}