Home > Backend Development > PHP Tutorial > foreach循环数组有关问题

foreach循环数组有关问题

WBOY
Release: 2016-06-13 12:54:56
Original
758 people have browsed it

foreach循环数组问题
$account 数组如下
Array
(
    [tencent] => Array
        (
            [0] => mylove_fish2008
            [1] => caochengli_love
        )

    [sina] => Array
        (
            [0] => 2935994540
            [1] => 3177446321
        )

    [163] => Array
        (
            [0] => 3395157578
            [1] => 8589895537
        )

    [sohu] => Array
        (
            [0] => 1400582280
            [1] => 1044720542
        )

)

我现在要循环这个数组,有两种方法
1.foreach ($account as $key => $rows)
  {
      foreach ($rows as $val)
      {
          echo $val.' ';
       }
   }

2.foreach ($account['tencent'] as $val)
  {
     echo $val.' ';
  }
  $account['sina'],$account['163'],$account['sohu']一样循环

循环这种二维数组,哪种效率高点


------解决方案--------------------
引用:
引用:设你的二维数组包含N个一位数组,一维数组中有M个键值,
那么完整的遍历一次例1时间复杂度
为O(N*M)
例2
O(M+M+M)(N个)=》O(N*M)
效率我觉得应该是一样的

// 两个循环
$t1 = microtime(true);
$data = array('tencent' => a……

确实如楼主所说,浏览器下例2的效率比例1快了将近一倍的时间,不过我认为楼主给的例1测试用例
$t1 = microtime(true);
 $data = array('tencent' => array('cadfdg', 'dfdgg'), 'sina' => array('111', '4654654'));
应该互换位置
下面是我的测试代码
<br>
	class runtime {  <br>
		public $StartTime = 0; <br>
		public $StopTime = 0;<br>
		<br>
		function get_microtime(){     <br>
			list($usec, $sec) = explode(' ', microtime());      <br>
			return ((float)$usec + (float)$sec);   <br>
		}  <br>
		<br>
		function start(){   <br>
			$this->StartTime = $this->get_microtime();   <br>
		 }  <br>
		 <br>
		function stop(){    <br>
			$this->StopTime = $this->get_microtime();   <br>
		}  <br>
		<br>
		function spent(){    <br>
			return round(($this->StopTime - $this->StartTime) * 1000, 4);     <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
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