PHP7与JS中将数字字符串及JSON格式字符串转为数组的最优方案咨询
Hey folks! Let's walk through the best ways to tackle your two programming questions. I've tested these approaches across PHP 7 and JavaScript to make sure they're efficient and reliable.
First up, converting a string of digits into an array. We'll cover two common scenarios: turning it into an array of string characters, or an array of actual numbers.
PHP 7 Solutions
- String character array: Use the built-in
str_split()function—it's purpose-built for this exact task and super efficient.$digitStr = "123456"; $strArray = str_split($digitStr); // Result: ["1", "2", "3", "4", "5", "6"] - Numeric element array: Wrap
str_split()witharray_map()to convert each string element to an integer.$digitStr = "123456"; $numArray = array_map('intval', str_split($digitStr)); // Result: [1, 2, 3, 4, 5, 6]
JavaScript Solutions
- String character array: The
split('')method is the go-to here—it splits the string at every empty string, giving you individual characters.const digitStr = "123456"; const strArray = digitStr.split(''); // Result: ["1", "2", "3", "4", "5", "6"] - Numeric element array: Use
Array.from()with a mapping function for a clean, concise approach, or chainmap(Number)tosplit('').// Option 1: Array.from const digitStr = "123456"; const numArray = Array.from(digitStr, Number); // Result: [1, 2, 3, 4, 5, 6] // Option 2: split + map const numArray2 = digitStr.split('').map(Number); // Same result as above
This one's all about safely parsing the JSON string into a native array, then optionally converting the string elements to numbers if needed.
PHP 7 Solution
PHP 7's json_decode() is fast and robust—just pass true as the second parameter to get an indexed array instead of an object. Always add error handling to catch malformed JSON!
$jsonStr = '["10","20","30","40"]'; // Parse JSON to array $stringArray = json_decode($jsonStr, true); // Check for parsing errors if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception("Failed to parse JSON: " . json_last_error_msg()); } // Convert to numeric array if needed $numericArray = array_map('intval', $stringArray); // Result: [10, 20, 30, 40]
JavaScript Solution
Use JSON.parse() to convert the JSON string to a JS array. Wrap it in a try/catch block to handle invalid JSON gracefully—this prevents your code from crashing if the input is bad.
const jsonStr = '["10","20","30","40"]'; let stringArray; try { stringArray = JSON.parse(jsonStr); } catch (error) { console.error("Invalid JSON string:", error.message); stringArray = []; // Fallback to empty array } // Convert to numeric array if needed const numericArray = stringArray.map(Number); // Result: [10, 20, 30, 40]
内容的提问来源于stack exchange,提问作者Mazen Embaby

