在PHP中将数组的第一个元素转换为字符串

时间:2023-02-15 21:44:22

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或内爆,但是在我的例子中数组只有一个条目。为什么我必须在一个只有一个条目的数组中使用组合值?

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?

如何将它转换成字符串?

13 个解决方案

#1


37  

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 first value of the array, even when there are multiple.

编辑:注意,array_shift并不是唯一返回单个值的函数。array_pop()、current()、end()、reset(),它们都将返回一个元素。所有发布的解决方案都可以工作。不过,使用数组移位,您可以确保只获得数组的第一个值,即使有多个值。

#2


29  

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:

是的,有。序列化()。它可以将各种数据类型(包括对象和数组)转换为字符串表示形式,稍后可以对其进行反序列化()。序列化一个关联数组(如数组(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"
                                                      // }

#3


12  

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

#4


9  

You can use the reset() function, it will return the first array member.

您可以使用reset()函数,它将返回第一个数组成员。

#5


7  

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.

内爆或连接(它们是完全相同的东西)在这里可以工作。或者,您可以调用array_pop并获取数组中唯一元素的值。

#6


6  

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
        )

)

#7


5  

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

或者你可以混合很多数组和vars

ob_start();
print_r($var1);
print_r($arr1);
echo "blah blah";
print_r($var2);
print_r($var1);
$your_string_var = ob_get_clean();

#8


5  

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美元。=(“笛子[我]美元美元,”);

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'

‘母亲’,‘父亲’,‘孩子’

#9


3  

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

由于只有在导出数组时才会出现空格问题,所以您可以对所有其他变量类型使用原始的var_export()。此函数执行此任务,并且从外部运行与var_export()相同。

<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>

http://www.php.net/manual/en/function.var-export.php#54440

http://www.php.net/manual/en/function.var-export.php # 54440

#10


3  

Convert an array to a string in PHP:

  1. Use the PHP join function like this:

    使用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;
    

    Which delimits the items in the array by comma into a string:

    将数组中的项以逗号分隔成字符串:

    4,1,8
    
  2. Or use the PHP implode function like this:

    或者使用PHP内爆函数:

    $my_array = array(4, 1, 8);
    echo implode($my_array);
    

    Which prints:

    打印:

    418
    
  3. Here is what happens if you join or implode key value pairs in a PHP array

    如果在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>
    

#11


3  

Use the inbuilt function in PHP, implode(array, separator):

使用PHP内建函数内爆(数组、分隔符):

<?php
    $ar = array("parth","raja","nikhar");
    echo implode($ar,"/");
?>

Result: parth/raja/nikhar

结果:parth /拉/ nikhar

#12


2  

Convert array to a string in PHP:

将数组转换为PHP中的字符串:

Use the PHP join function like this:

使用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;

Which delimits the items in the array by comma into a string:

将数组中的项以逗号分隔成字符串:

4,1,8

#13


1  

For completeness and simplicity sake, the following should be fine:

为了完整性和简单起见,下面应该是:

$str = var_export($array, true);

It does the job quite well in my case, but others seem to have issues with whitespace. In that case, the answer from ucefkh provides a workaround from a comment in the PHP manual.

它在我的例子中做得很好,但是其他人似乎对空格有问题。在这种情况下,来自ucefkh的答案提供了PHP手册中注释的变通方法。

#1


37  

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 first value of the array, even when there are multiple.

编辑:注意,array_shift并不是唯一返回单个值的函数。array_pop()、current()、end()、reset(),它们都将返回一个元素。所有发布的解决方案都可以工作。不过,使用数组移位,您可以确保只获得数组的第一个值,即使有多个值。

#2


29  

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:

是的,有。序列化()。它可以将各种数据类型(包括对象和数组)转换为字符串表示形式,稍后可以对其进行反序列化()。序列化一个关联数组(如数组(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"
                                                      // }

#3


12  

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

#4


9  

You can use the reset() function, it will return the first array member.

您可以使用reset()函数,它将返回第一个数组成员。

#5


7  

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.

内爆或连接(它们是完全相同的东西)在这里可以工作。或者,您可以调用array_pop并获取数组中唯一元素的值。

#6


6  

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
        )

)

#7


5  

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

或者你可以混合很多数组和vars

ob_start();
print_r($var1);
print_r($arr1);
echo "blah blah";
print_r($var2);
print_r($var1);
$your_string_var = ob_get_clean();

#8


5  

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美元。=(“笛子[我]美元美元,”);

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'

‘母亲’,‘父亲’,‘孩子’

#9


3  

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

由于只有在导出数组时才会出现空格问题,所以您可以对所有其他变量类型使用原始的var_export()。此函数执行此任务,并且从外部运行与var_export()相同。

<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>

http://www.php.net/manual/en/function.var-export.php#54440

http://www.php.net/manual/en/function.var-export.php # 54440

#10


3  

Convert an array to a string in PHP:

  1. Use the PHP join function like this:

    使用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;
    

    Which delimits the items in the array by comma into a string:

    将数组中的项以逗号分隔成字符串:

    4,1,8
    
  2. Or use the PHP implode function like this:

    或者使用PHP内爆函数:

    $my_array = array(4, 1, 8);
    echo implode($my_array);
    

    Which prints:

    打印:

    418
    
  3. Here is what happens if you join or implode key value pairs in a PHP array

    如果在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>
    

#11


3  

Use the inbuilt function in PHP, implode(array, separator):

使用PHP内建函数内爆(数组、分隔符):

<?php
    $ar = array("parth","raja","nikhar");
    echo implode($ar,"/");
?>

Result: parth/raja/nikhar

结果:parth /拉/ nikhar

#12


2  

Convert array to a string in PHP:

将数组转换为PHP中的字符串:

Use the PHP join function like this:

使用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;

Which delimits the items in the array by comma into a string:

将数组中的项以逗号分隔成字符串:

4,1,8

#13


1  

For completeness and simplicity sake, the following should be fine:

为了完整性和简单起见,下面应该是:

$str = var_export($array, true);

It does the job quite well in my case, but others seem to have issues with whitespace. In that case, the answer from ucefkh provides a workaround from a comment in the PHP manual.

它在我的例子中做得很好,但是其他人似乎对空格有问题。在这种情况下,来自ucefkh的答案提供了PHP手册中注释的变通方法。