微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php 代码优化之经典示例

我用的方法是按key区分块,然后在将块赋给其他的变量,然后再进行一些操作,这样用到了很多的for和foreach,而且代码量也很大,所以被退回来了。 经过上面的指导,发现真的好简单,现在与大家一同分享

decoration: underline">

ID


decoration: underline">

FIELD1


decoration: underline">

FIELD2

decoration: underline">

FIELD3

decoration: underline">

FIELD4

decoration: underline">

Key


1
*** *** *** *** meat1
2
*** *** *** *** meat1
3
*** *** *** *** meat1
4 *** *** *** *** meat1
5
*** *** *** *** fruit2
6 *** *** *** *** fruit2
7
*** *** *** *** fruit2
8
*** *** *** *** fruit2
9
*** *** *** *** fruit2
10
*** *** *** *** food3
11
*** *** *** *** food3

现在有如上所示的结果

要求:要对这个已经按key进行排序了的数组进行操作,相同key的项进行处理。

提示:这个是很典型的母子表的结构,也就是说其实它是两张表的合并,可以这样处理成两个数组,方便数组里面对块的操作
array1:ID|Key

decoration: underline">

ID


decoration: underline">

Key


1
meat1
2
meat1
3
meat1
4 meat1
5
fruit2
6 fruit2
7
fruit2
8
fruit2
9
fruit2
10
food3
11
food3

array2:key => array(ID,FIELD1,FIELD2,FIELD3,FIELD4,FIELD5,Key)


decoration: underline">


decoration: underline">


decoration: underline">

decoration: underline">

decoration: underline">

decoration: underline">


meat1=>
1
*** *** *** *** meat1
2
*** *** *** *** meat1
3
*** *** *** *** meat1
4 *** *** *** *** meat1
fruit2=> 5
*** *** *** *** fruit2
6 *** *** *** *** fruit2
7
*** *** *** *** fruit2
8
*** *** *** *** fruit2
9
*** *** *** *** fruit2
food3=> 10
*** *** *** *** food3
11
*** *** *** *** food3

实现如上数组分离代码

这样后,访问tempArray的块数据就非常方便了

foreach($tempArray as $row){

  array1[$row['ID']] = $row['Key'];

  array2[$row['Key']][] = $row;

}

访问和处理代码

foreach($array1 as $ID => $Key){

  $this->doSomeThing($ID);

  

  $this->doSomeThing2();

}

原文地址:https://www.jb51.cc/php/28093.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐