Home > Backend Development > PHP Problem > How to convert php string to two-dimensional array

How to convert php string to two-dimensional array

藏色散人
Release: 2023-03-03 07:52:01
Original
3623 people have browsed it

How to convert php string to a two-dimensional array: first create a PHP sample file; then use the explode function to break up the string into an array; then check whether "$data" is empty; finally run the file. Can.

How to convert php string to two-dimensional array

php splits the string into a two-dimensional array

Specific question:

I want to talk about a string, the format is roughly: "Number" Space "Quantity" Enter "Number" "Space" "Quantity" Enter... Such data is stored in a two-dimensional array. Finally write to the database. Use php. Please tell me how to operate?

The number of data rows is not certain. It may be 1 line, or it may be more than 10 lines.

$str="123 5
456 5
159 6";
数组格式
$order = array
(
"1"=>array
(
"123",
"5"
),
"2"=>array
(
"456".
"5"
),
"3=>array
(
"159",
"6"
)
);
Copy after login

Solution:

If the data comes from a file, it is easy to operate. Below is an example of data that does not come from a file

 <?php
if($_POST){
 $arr=explode("\n",$_POST["test"]);
 $result=array();
 foreach($arr as $data){
  trim($data) && $result[]=explode(" ",$data); //首先要检查$data是否为空
 }
 print_r($result);
}
?> 
<form action="a.php" method="post">
<textarea name="test" style="width:500px;height:200px;"></textarea>
<input type="submit" value="提交" />
</form>
Copy after login

Recommendation: "PHP Tutorial"

The above is the detailed content of How to convert php string to two-dimensional array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template