foreach for a multidimensional array

时间:2013-07-03 07:53:29

标签: php arrays foreach

我正在尝试循环一个多维数组,并且不太确定这是如何完成的。

$array = array(array('product1'=>'url1'));
$array[] = array('product2'=>'url2');
$array[] = array('product3'=>'url3');

foreach($array as $name=>$url)
{
echo '<a href="'.$url.'">'.$name.'</a>';
}

返回, 注意:第15行的test.php中的数组到字符串转换

0

注意:第15行的test.php中的数组到字符串转换

1

注意:第15行的test.php中的数组到字符串转换

2

我在这里错过了什么吗?

2 个答案:

答案 0 :(得分:2)

请不要使用$ array作为变量名..如果它是这样的话会好得多。

$products = array(
  array('product1' => 'url1'),
  array('product2' => 'url2'),
  array('product3' => 'url3')
);

拉取数据:

foreach($products as $ind){

  ....

  foreach($ind as $name){
  ....

  }
}

答案 1 :(得分:0)

currentpage.php

//this is required array which you want to enter in session  
$array = array(
      "product1" => "url1",
      "product2" => "url2",
      "product3" => "url3"
   );

session_start();//here we start a session 
$_SESSION['product_url']=$array;//here we pass required array to session

//By the help of below code we check is session contain array
//echo "<pre>";
//print_r($_SESSION);

requiedpage.php

session_start();//here we start a session
//finally display required data to reqired page... 
foreach($_SESSION['product_url'] as $key=>$value)
{
    echo '<a href="'.$value.'">'.$key.'</a><br>';
}

用于多维数组: -

currentpage.php
    //this is required multidimensional array which you want to enter in session  
        $array= array(
                "[0]"=>array("product1" => 'url1',"product2" => 'url2',"product3" => 'url3')
            );
requieredpage.php
        foreach($_SESSION['product_url'] as $key=>$value)
        {
            foreach($value as $k=>$v){
                echo '<a href="'.$v.'">'.$k.'</a><br>';
            }    
        }

输出我得到了: -

product1
product2
product3