数组每行爆炸和匹配/使用表行

时间:2013-02-19 09:16:26

标签: 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]);

}

我想要像这样的输出

3 = 3 = Male

2 = 2 = 21

1 = 1 = Samuel Pulta

2 个答案:

答案 0 :(得分:0)

<?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

答案 1 :(得分:0)

我宁愿使用preg_match_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数组中打印相应的值。