循环遍历数组

时间:2013-03-15 18:34:09

标签: php

我的问题是如何在循环遍历变量时将数组值粘贴到变量中。

我用它来获取我的数组 - 我需要查询中的两个值。

$categ = array();   
while ($row = mysql_fetch_array($result)) {
    array_push($categ, array(
        'cat' => $row["CategoryName"],
        'course' => $row["Course"]
    ));
}

这里有重复项,所以我使用以下内容来获取一个独特的数组:

$categ = array_map("unserialize", array_unique(array_map("serialize", $categ)));

这给出了以下输出:

Array (
  [0] => Array ( [cat] => Dogs [course] => Kempton Park )
  [2] => Array ( [cat] => Dogs [course] => Lingfield Park )
  [4] => Array ( [cat] => Gallops [course] => Wincanton )
) 

然后我想循环遍历这个数组,将[cat]和[course]的值分配给两个变量:$cat$course

我已经尝试了各种但它不起作用:下面给出了语法错误 - 不确定原因??

foreach ($categ as list($cat2, $course2)){
    require ('C04_by_Account_by_Bet.php');
};

3 个答案:

答案 0 :(得分:0)

您不能在list()中使用foreach。你需要这样做:

foreach ($categ as $value){
    list($cat2, $course2) = $value;
}

编辑:您可以在PHP 5.5中执行foreach ($categ as list($cat2, $course2)){

答案 1 :(得分:0)

$categ = array();   
while ($row = mysql_fetch_array($result)) {
    $obj = new stdClass();
    $obj->cat = $row["CategoryName"];
    $obj->course = $row["Course"];
    $categ[] = $obj;
}

foreach($categ as $thing)
{
    $thing->cat;
    $thing->course;
}

我会推荐这样的东西。

编辑:甚至更好

$categ = array();   
while ($obj = mysql_fetch_object($result)) {
    $categ[] = $obj;
}

foreach($categ as $thing)
{
    $thing->cat;
    $thing->course;
}

答案 2 :(得分:0)

我们也可以这样做:

$categ = array();   
while ($row = mysql_fetch_array($result)) {
    $categ[$row["CategoryName"]][] = $row["Course"];
}

数组将是

Array (
  [Dogs] => Array ( Kempton Park, Lingfield Park ),
  [Gallops] => Array ( Wincanton )
) 

然后你可以这样做:

foreach($categ as $category => $courses) {
   $courses = array_unique($courses);
   foreach($courses as $course) {
      echo $category . ' : ' . $course; //or any other action
   }
}