PHP - 字符串到(多)数组 - 和循环

时间:2014-05-29 14:39:46

标签: php arrays

抱歉,我不知道如何解决这个问题,实际上我也找不到合适的词来搜索解决方案:)

我有一个字符串,如下所示

picture1.jpg, name1, role1; picture2.jpg, name2, role2; picture3.jpg, name2, role2;

我是否可以通过循环来获得类似的东西

loop start
<img src='$image' />$name as $role
loop ends

3 个答案:

答案 0 :(得分:1)

试试这个:

    $str = 'picture1.jpg, name1, role1; picture2.jpg, name2, role2; picture3.jpg, name2, role2;';
    $items = explode(';', $str);
    foreach ($items as $row) {
        $arr = explode(',', $row);
        echo sprintf('<img src="%s"/> %s as %s', trim($arr[0]),trim($arr[1]),trim($arr[2]));
    }

答案 1 :(得分:1)

完整的解决方案将是:

function output($input) {

  $output = '';

  $segments = explode(';', $input);

  if (count($segments))
  {
    foreach ($segments as $segment)
    {
      $values = explode(',', $segment);

      if (count($values) === 3)
      {
        $values = array_map(function($value) {
          return trim($value);
        }, $values);

        $output .= '<img src="'.$values[0].'">';
        $output .= ' '.$values[1];
        $output .= ' as '.$values[2];
      }
    }
  }

  return $output;
}

$input = "picture1.jpg, name1, role1; picture2.jpg, name2, role2; picture3.jpg, name2, role2;";

echo output($input);

答案 2 :(得分:0)

试试这个简短的版本:

$str = 'picture1.jpg, name1, role1; picture2.jpg, name2, role2; picture3.jpg, name2, role2;';

function picture_name_role ($val) {
    $pnr = array_filter(explode(',', $val));
    list($picture, $name, $role) = $pnr;
    return '<img src="' . trim($picture) . '"/>' . trim($name) . ' as ' . trim($role);
}

$f = array_map('picture_name_role', array_filter(explode(';', $str)));

var_dump($f);