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


PHP - String to (multi) Array - and loop

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

我有一个字符串如下

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

有没有办法让它循环得到这样的东西

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

试试这个:

    $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]));
    }

一个完整的解决方案是:

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);

试试这个简短的版本:

$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);