2013-06-30 32 views
3

我有这个PHP数组:如何格式化PHP数组字符串

$items = array (
    "Item 1" => "Value 1", 
    "Item 2" => "Value 2", 
    "Item 3" => "Value 3" 
); 

而且我不知道是否有一个优雅的PHP函数我从来没有听说过这样做,因为这:

$output = ""; 
foreach ($items as $key => $value) { 
    $output .= sprintf("%s: %s\n" , $key , $value); 
} 
echo $output; 

这当然会输出:

Item 1: Value 1 
Item 2: Value 2 
Item 3: Value 3 

还有,你叫什么呢?反序列化?

+4

你需要类似'var_dump'或'print_r'的东西吗? –

+3

因为您每次都会将'$ output'重新设置为当前值,所以这不会真正输出您想要的内容。 – cheesemacfly

+0

有格式化print_r的脚本,但你可以像上面那样做,对我来说看起来很好 – 2013-06-30 23:42:25

回答

5

总是有array_walk函数。你的例子可能是这个样子:

function test_print($value, $key) { 
    echo sprintf("%s: %s\n" , $key , $value); 
} 

$items = array (
    "Item 1" => "Value 1", 
    "Item 2" => "Value 2", 
    "Item 3" => "Value 3" 
); 

array_walk($items, 'test_print'); 

定义你的功能后,您可以然后再用array_walk($items, 'test_print');需要整个代码。如果你正在处理多维数组,那么还有array_walk_recursive函数。

+0

这是一个非常棒的方式。我喜欢简化它,它使代码更容易理解。 –

1

您的解决方案没有任何问题,只是您缺少拼接运算符。

$output = ""; 
foreach ($items as $key => $value) { 
    $output .= sprintf("%s: %s\n" , $key , $value); 
} 
echo $output; 

请记住,这只能处理单维数组。

在PHP中有这么多的内置函数,我们有时会忘记我们实际上必须编写代码。在评论中提到您可以使用array_ *函数之一,例如array_reduce,但与您的解决方案相比,这只会导致更多的复杂性。