gpt4 book ai didi

php - 字符串到整数数组php

转载 作者:可可西里 更新时间:2023-11-01 12:40:33 25 4
gpt4 key购买 nike

我想在 php 中将字符串(例如 1,2,3,4,5,6)转换为整数数组?我发现函数只能访问字符串的第一个字符,例如 1。如何将整个字符串转换为数组?

function read_id_txt()
{

$handle_file = fopen("temporalfile.txt", 'r');

$i=0;

while ($array_var[$i] = fgets($handle_file, 4096)) {
echo "<br>";
print_r($array_var[i]);
$i++;
}

fclose($handle_file);

$temp=explode(" ", $array_var[0]);

return $temp;


}

最佳答案

使用 PHP 的 explode .

$str = "1,2,3,4,5,6";
$arr = explode("," $str); // array( '1', '2', '3', '4', '5', '6' );

foreach ($arr AS $index => $value)
$arr[$index] = (int)$value;

// casts each value to integer type -- array( 1, 2, 3, 4, 5, 6 );

根据 Tim Cooper 的建议, 使用 array_walk比上面的循环更简单:

array_walk($arr, 'intval');

关于php - 字符串到整数数组php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8963910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com