开发者

php optimizing code for foreach

开发者 https://www.devze.com 2023-03-15 02:41 出处:网络
I\'m developing something like a simple and purpose-specific cms. I\'m using a db class that outputs an array as a result from the query, but this array varies in structure depending on the mysql_num

I'm developing something like a simple and purpose-specific cms.

I'm using a db class that outputs an array as a result from the query, but this array varies in structure depending on the mysql_num_rows.

If there is on开发者_如何学JAVAly one result it outputs a simple array, otherwise it outputs a nested array.

So, I must check the structure of the array to decide whether to do a loop with foreach, or just print the results.

with simple mysql_fetch_assoc we can use while() and then there is no problem with the number of rows. but with an array we must check it.

Till now everything is OK.

The problem is that the code will be repeated for the two conditions. with a slight change in the array name.

The array name is $res, if one result it will be $res['anything here'], else, because we have to use foreach($res as $row), the array will be $row['anything here'].

So the code looks ugly and very big. Please take a lool at it here: http://mohamedkadri.com/code.html and tell me how to make it simpler and smaller.


The solution is simple:

Change your DB layer so you can force it to return a list of rows even if there's just a single row. That's the only proper solution.


This is not a great approach. I'd suggest changing your DB class so you have a different method to call depending on whether the query will return one row or multiple. E.g. in the Zend Framework database classes there is fetchRow and fetchAll. This will make it much easier for you to deal with the data you get back.

Another option might be to just always return a nested array even if there was only one row. That way the code to process the data will always be the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号