在单个字符串中打印PHP数组值

时间:2013-04-17 18:58:28

标签: php arrays string

我有一个数组,我加载如下:

foreach ($_SESSION['cart'] as $item) 
{
  $pid = $item['itemId'];
  $q = $item['qty']; 
  $orderedItems[]=array('itemId'=>$pid,'qty'=>$q);
}

我现在需要创建一个变量,将我的数组结果存储在一个字符串中,如下所示:

"For itemA ==> 2 sample
For itemB ==> 1 sample"

2 个答案:

答案 0 :(得分:1)

$string = join("\n", array_map(function($x) {return "For $x[itemId] ==> $x[qty] sample";}, $orderedItems));

答案 1 :(得分:0)

$string = "";
foreach ($orderedItems as $item)
    $string .= "For item{$item['itemId']} ==> {$item['qty']} sample\n";
$string = rtrim($string);