Home >Backend Development >PHP Tutorial >Summary of Thinkphp's method of converting a two-dimensional array into a one-dimensional array suitable for tags
This article mainly introduces Thinkphp's method of converting a two-dimensional array into a one-dimensional array suitable for tags, and summarizes the common array conversion methods. It is very practical. Friends who need it can refer to it
Summary of examples of this article Thinkphp converts a two-dimensional array into a one-dimensional array suitable for tags. Share it with everyone for your reference. The specific implementation method is as follows:
Method 1:
Copy code The code is as follows:
$projectList=arr1tag($projectList,array('','请选择'),'project_name'); //其中$list为传值过来的二维数组,$default为默认值,$k为指定的表字段 function arr1tag($list,$default='',$k=''){ $tmp=''; if(array($list)){ if(array($default)){ $tmp[$default[0]]=$default[1]; } foreach ($list as $k1=>$v1){ $tmp[$k1+1]=$v1[$k]; } } return $tmp; }
Method two:
Copy code The code is as follows:
$projectList=arr2tag($projectList,array('','请选择'),''); //根据数组下标获取对应值 function array_index2val($array,$index=0){ $value=''; if(is_array($array)){ $i=0; foreach($array as $val){ if($i===$index){ $value=$val; break; } $i++; } } return $value; } //把数据库中调出的数组转换成可以使用模版标签的数组,其中$default为默认值,$k为指定的表字段 function arr2tag($arr,$default=NULL,$K=NULL){ $tmp=''; if(is_array($arr)){ if(is_array($default)){ $tmp[$default[0]]=$default[1]; if($type==1){ $tmp[$default[2]]=$default[3]; } } foreach ($arr as $key=>$val){ if(is_array($K)){ $tmp[$val[$K[0]]]=$val[$K[1]]; }else{ $tmp[array_index2val($val,0)]=array_index2val($val,1); } } } return $tmp; }
Method three:
will read the database The content is directly converted into a one-dimensional array. This method is mostly used for select tags
Copy code The code is as follows:
$this->where($where)->getField('id,name'); 得出的内容为 array( 'id' => 'name', )
Related recommendations:
thinkphp5 beanbun implements simple crawling of movie URLs and pictures
The use of behaviors in ThinkPHP5
The above is the detailed content of Summary of Thinkphp's method of converting a two-dimensional array into a one-dimensional array suitable for tags. For more information, please follow other related articles on the PHP Chinese website!