一、将字符串转换成数组
1.1 使用 explode 函数
explode 函数可以将字符串按照指定的分隔符拆分成数组,示例代码如下:
$str = apple,banana,orange;$arr = explode(,, $str);print_r($arr);
输出结果:
array( [0] => apple [1] => banana [2] => orange)
1.2 使用 str_split 函数
str_split 函数可以将字符串拆分成单个字符的数组,示例代码如下:
$str = hello, php!;$arr = str_split($str);print_r($arr);
输出结果:
array( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => , [6] => [7] => p [8] => h [9] => p [10] => !)
二、将数字、布尔值或 null 转换成数组
2.1 使用转换符
可以使用转换符将数字、布尔值或 null 转换成数组,示例代码如下:
$num = 123;$arr = (array)$num;print_r($arr);$bool = true;$arr = (array)$bool;print_r($arr);$null = null;$arr = (array)$null;print_r($arr);
输出结果:
array( [0] => 123)array( [0] => 1)array()
三、将对象转换成数组
3.1 使用 get_object_vars 函数
get_object_vars 函数可以将对象转换成关联数组,其中键名为对象属性名,示例代码如下:
class person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; }}$person = new person(tom, 18);$arr = get_object_vars($person);print_r($arr);
输出结果:
array( [name] => tom [age] => 18)
3.2 嵌套使用转换
如果对象属性值也是对象,可以使用递归调用将其转换成数组,示例代码如下:
class person { public $name; public $age; public $address; public function __construct($name, $age, $address) { $this->name = $name; $this->age = $age; $this->address = $address; }}class address { public $country; public $city; public function __construct($country, $city) { $this->country = $country; $this->city = $city; }}$address = new address(china, beijing);$person = new person(tom, 18, $address);$arr = (array)$person;if (is_object($person->address)) { $arr[address] = (array)$person->address;}print_r($arr);
输出结果:
array( [name] => tom [age] => 18 [address] => array ( [country] => china [city] => beijing ))
以上就是将变量转换成数组的方法,希望能对你有所帮助!
以上就是php 怎么将变量转换成数组的详细内容。
