php PHP中将数组的第一个元素转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6262186/
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
Convert the first element of an array to a string in PHP
提问by Daric
I have a PHP array and want to convert it to a string.
我有一个 PHP 数组,想将其转换为字符串。
I know I can use join
or implode
, but in my case array has only one item. Why do I have to use combine values in an array with only one item?
我知道我可以使用join
or implode
,但就我而言,数组只有一项。为什么我必须在只有一项的数组中使用组合值?
This array is the output of my PHP function which returns an array:
这个数组是我的 PHP 函数的输出,它返回一个数组:
Array(18 => 'Something');
How do I convert this to a string?
如何将其转换为字符串?
采纳答案by Berry Langerak
Is there any other way to convert that array into string ?
有没有其他方法可以将该数组转换为字符串?
You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.
您不想将数组转换为字符串,而是想获取数组唯一元素的值(如果我正确阅读)。
<?php
$foo = array( 18 => 'Something' );
$value = array_shift( $foo );
echo $value; // 'Something'.
?>
Using array_shift you don't have to worry about the index.
使用 array_shift 你不必担心索引。
EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the firstvalue of the array, even when there are multiple.
编辑:请注意,array_shift 不是唯一返回单个值的函数。array_pop()、current()、end()、reset(),它们都将返回单个元素。所有发布的解决方案都有效。但是使用数组移位,您可以确保您只会获得数组的第一个值,即使有多个。
回答by Salman A
Is there any other way to convert that array into string ?
有没有其他方法可以将该数组转换为字符串?
Yes there is. serialize()
. It can convert various data types (including object and arrays) into a string representation which you can unserialize()
at a later time. Serializing an associative array such as Array(18 => 'Somthing')
will preserve both keys and values:
就在这里。serialize()
. 它可以将各种数据类型(包括对象和数组)转换为您以后可以使用的字符串表示形式unserialize()
。序列化关联数组,例如Array(18 => 'Somthing')
将保留键和值:
<?php
$a = array(18 => 'Something');
echo serialize($a); // a:1:{i:18;s:9:"Something";}
var_dump(unserialize('a:1:{i:18;s:9:"Something";}')); // array(1) {
// [18]=>
// string(9) "Something"
// }
回答by Sven Simon
A simple way to create a array to a PHP string array is:
为 PHP 字符串数组创建数组的一种简单方法是:
<?PHP
$array = array("firstname"=>"John", "lastname"=>"doe");
$json = json_encode($array);
$phpStringArray = str_replace(array("{", "}", ":"),
array("array(", "}", "=>"), $json);
echo phpStringArray;
?>
回答by Paolo Stefan
回答by John Hargrove
implode
or join
(they're the exact same thing) would work here. Alternatively, you can just call array_pop
and get the value of the only element in the array.
implode
或者join
(它们是完全一样的)会在这里工作。或者,您可以调用array_pop
并获取数组中唯一元素的值。
回答by Jonatan Ienco
If your goal is output your array to a string for debbuging: you can use the print_r()function, which receives an expression parameter (your array), and an optional boolean return parameter. Normally the function is used to echo the array, but if you set the return parameter as true, it will return the array impression.
如果您的目标是将数组输出到字符串进行调试:您可以使用print_r()函数,该函数接收一个表达式参数(您的数组)和一个可选的布尔返回参数。通常该函数用于回显数组,但如果您将返回参数设置为true,它将返回数组印象。
Example:
例子:
//We create a 2-dimension Array as an example
$ProductsArray = array();
$row_array['Qty'] = 20;
$row_array['Product'] = "Cars";
array_push($ProductsArray,$row_array);
$row_array2['Qty'] = 30;
$row_array2['Product'] = "Wheels";
array_push($ProductsArray,$row_array2);
//We save the Array impression into a variable using the print_r function
$ArrayString = print_r($ProductsArray, 1);
//You can echo the string
echo $ArrayString;
//or Log the string into a Log file
$date = date("Y-m-d H:i:s", time());
$LogFile = "Log.txt";
$fh = fopen($LogFile, 'a') or die("can't open file");
$stringData = "--".$date."\n".$ArrayString."\n";
fwrite($fh, $stringData);
fclose($fh);
This will be the output:
这将是输出:
Array
(
[0] => Array
(
[Qty] => 20
[Product] => Cars
)
[1] => Array
(
[Qty] => 30
[Product] => Wheels
)
)
回答by mexican_75
You could use print_r and html interpret it to convert it into a string with newlines like this:
您可以使用 print_r 和 html 解释它以将其转换为带有换行符的字符串,如下所示:
$arraystring = print_r($your_array, true);
$arraystring = '<pre>'.print_r($your_array, true).'</pre>';
Or you could mix many arrays and vars if you do this
或者你可以混合许多数组和变量,如果你这样做
ob_start();
print_r($var1);
print_r($arr1);
echo "blah blah";
print_r($var2);
print_r($var1);
$your_string_var = ob_get_clean();
回答by BARIS KURT
A For()
loop is very useful. You can add your array's value to another variable like this:
一个For()
循环是非常有用的。您可以将数组的值添加到另一个变量中,如下所示:
<?php
$dizi=array('mother','father','child'); //This is array
$sayi=count($dizi);
for ($i=0; $i<$sayi; $i++) {
$dizin.=("'$dizi[$i]',"); //Now it is string...
}
echo substr($dizin,0,-1); //Write it like string :D
?>
In this code we added $dizi's values and comma to $dizin:
在这段代码中,我们将 $dizi 的值和逗号添加到 $dizin 中:
$dizin.=("'$dizi[$i]',");
$dizin.=("'$dizi[$i]',");
Now
现在
$dizin = 'mother', 'father', 'child',
It's a string, but it has an extra comma :)
这是一个字符串,但它有一个额外的逗号:)
And then we deleted the last comma, substr($dizin, 0, -1);
然后我们删除了最后一个逗号, substr($dizin, 0, -1);
Output:
输出:
'mother','father','child'
“妈妈”、“爸爸”、“孩子”
回答by Eric Leschinski
Convert an array to a string in PHP:
在 PHP 中将数组转换为字符串:
Use the PHP
join
function like this:$my_array = array(4, 1, 8); print_r($my_array); Array ( [0] => 4 [1] => 1 [2] => 8 ) $result_string = join(',', $my_array); echo $result_string;
Which delimits the items in the array by comma into a string:
4,1,8
Or use the PHP
implode
function like this:$my_array = array(4, 1, 8); echo implode($my_array);
Which prints:
418
Here is what happens if you join or implode key value pairs in a PHP array
php> $keyvalues = array(); php> $keyvalues['foo'] = "bar"; php> $keyvalues['pyramid'] = "power"; php> print_r($keyvalues); Array ( [foo] => bar [pyramid] => power ) php> echo join(',', $keyvalues); bar,power php> echo implode($keyvalues); barpower php>
join
像这样使用 PHP函数:$my_array = array(4, 1, 8); print_r($my_array); Array ( [0] => 4 [1] => 1 [2] => 8 ) $result_string = join(',', $my_array); echo $result_string;
它用逗号将数组中的项目分隔成一个字符串:
4,1,8
或者
implode
像这样使用 PHP函数:$my_array = array(4, 1, 8); echo implode($my_array);
哪个打印:
418
如果您在 PHP 数组中加入或内爆键值对,会发生以下情况
php> $keyvalues = array(); php> $keyvalues['foo'] = "bar"; php> $keyvalues['pyramid'] = "power"; php> print_r($keyvalues); Array ( [foo] => bar [pyramid] => power ) php> echo join(',', $keyvalues); bar,power php> echo implode($keyvalues); barpower php>
回答by Parth Chavda
Use the inbuilt function in PHP, implode(array, separator)
:
使用 PHP 中的内置函数,implode(array, separator)
:
<?php
$ar = array("parth","raja","nikhar");
echo implode($ar,"/");
?>
Result: parth/raja/nikhar
结果:parth/raja/nikhar