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

How to convert php string to two-dimensional array

藏色散人
藏色散人Original
2020-07-24 09:20:323563browse

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"
)
);

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>

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!

Statement:
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