php 将数组转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1115835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:07:56  来源:igfitidea点击:

Convert an array to a string

phparraysstring

提问by Jayu

Possible Duplicate:
Convert PHP array string into an array

可能的重复:
将 PHP 数组字符串转换为数组

Which function can be used to convert an array into a string, maintaining your ability to return the string into an array?

哪个函数可用于将数组转换为字符串,并保持将字符串返回为数组的能力?

回答by Gumbo

The serializefunctionturns any value into a string.

serialize函数将任何值转换为字符串。

回答by spas

You can use the implode()function to convert an array into a string:

您可以使用该implode()函数将数组转换为字符串:

$array = implode(" ", $string); //space as glue

If you want to convert it back to an array you can use the explode function:

如果要将其转换回数组,可以使用爆炸函数:

$string = explode(" ", $array); //space as delimiter

回答by karim79

Just to add, there's also the var_exportfunction. I've found this useful for certain situations. From the manual:

补充一点,还有这个var_export功能。我发现这对某些情况很有用。从手册:

var_export — Outputs or returns a parsable string representation of a variable

var_export — 输出或返回变量的可解析字符串表示

Example:

例子:

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

Returns this output (which can then be converted back to an array using eval()):

返回此输出(然后可以使用eval()将其转换回数组):

array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)

回答by joe

function makestring($array)
  {
  $outval = '';
  foreach($array as $key=>$value)
    {
    if(is_array($value))
      {
      $outval .= makestring($value);
      }
    else
      {
      $outval .= $value;
      }
    }
  return $outval;
  }