【问题标题】:Convert a string to an array of only a single element将字符串转换为仅包含单个元素的数组
【发布时间】:2015-07-27 12:32:50
【问题描述】:

我的代码是:

<?php
$input = array('item1' => 'object1', 'item2' => 'object2', 'item-n' =>     'object-n');
$output = implode(',' ,$input);
print $output;
?>

我的输出:

object1,object2,object-n

这是一个字符串。我需要这个字符串是一个数组。(如下所示)。

Array(object1,object2,object-n);

这可能吗?

输出:数组 ( [0] => object1,object2,object-n ) 不正确,因为字符串存储为第一个元素.....我需要这个...

Array(object1,object2,object-n);....the only element of the array... 

任何帮助..

【问题讨论】:

  • 你的意思是创建一个只有一个元素的数组吗?
  • 只需更改$output = array(implode(',' ,$input);)$output[] = implode(',' ,$input);
  • Array ( [0] => object1,object2,object-n )....... 这个输出不正确,因为字符串存储在第一个元素...... ..我需要这个...Array(object1,object2,object-n);..数组的唯一元素...
  • 不清楚你在问什么。如果你需要无键数组,你应该使用array_values()方法。

标签: php


【解决方案1】:

只需使用array_values()即可

$input = array('item1' => 'object1', 'item2' => 'object2', 'item-n' => 'object-n');
$new_array = array_values($input);

print '<pre>';
print_r($new_array);
print '</pre>';

【讨论】:

  • 抱歉……这不是我需要的答案……像这样的 Array(object1,object2,object-n);
【解决方案2】:

使用explode将字符串转换为数组。

$input1 = "obj,obj1";
$objarr = explode( ',', $input1 );

var_dump($objarr)

【讨论】:

  • 我正好需要 Array(object1,object2,object-n);
【解决方案3】:

关于您的问题,您可以运行以下两个脚本之一:

1.

<?php
$input = array('item1' => 'object1', 'item2' => 'object2', 'item-n' =>'object-n');
//$output = implode(',' ,$input);
print_r(array_values($input));
?>

2.

<?php
$input = array('item1' => 'object1', 'item2' => 'object2', 'item-n' =>'object-n');
$output = implode(',' ,$input);
$array = array($output);
print_r($array);
?>

希望对你有帮助。

【讨论】:

  • 两个代码都不起作用......我需要完全一样......Array(object1,object2,object-n);....数组的唯一元素......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
相关资源
最近更新 更多