php foreach循环只显示数组的第一个字母

时间:2014-02-06 01:27:40

标签: php arrays foreach

$item= "stackoverflow";
$price = "30.00";

$cs1_array = array();
$cs1_array['item'] = $item;
$cs1_array['price'] = $price;

    if($cs1_array > 0){
            echo "<table>";
            foreach ($cs1_array as $item){
                echo "<tr>";
                echo "<td>{$item['item']}</td><td>{$item['price']}</td>";
                echo "</tr>";
            }
            echo "</table>";
        }

这将仅输出数组的第一个字母。示例它将仅显示stackoverflow的字母s。我想显示整个stackoverflow字,怎么做?

2 个答案:

答案 0 :(得分:2)

你确实创建了一个单级数组,而你需要的是一个多维数组(即数组中的数组):

$cs1_array = array();
$cs1_array[] = array(
    'item' => $item,
    'price' => $price
);

比较一下:

// wrong
array(2) {
  ["item"]=>
  string(13) "stackoverflow"
  ["price"]=>
  string(5) "30.00"
}

VS

// right
array(1) {
  [0]=>
  array(2) {
    ["item"]=>
    string(13) "stackoverflow"
    ["price"]=>
    string(5) "30.00"
  }
}

答案 1 :(得分:1)

如果您的数组中只有一个item和一个price,则根本不需要循环:

$item= "stackoverflow";
$price = "30.00";

$cs1_array = array();
$cs1_array['item'] = $item;
$cs1_array['price'] = $price;

    if(sizeof($cs1_array) > 0){
            echo "<table>";
            echo "<tr>";
            echo "<td>{$cs1_array['item']}</td><td>{$cs1_array['price']}</td>";
            echo "</tr>";
            echo "</table>";
    }

但是,如果您想拥有itemprice的多个实例,则需要一个数组数组:

$cs1_array = array();
$cs1_array[] = array(
    "item" => "stackoverflow",
    "price" => "30.00"
);
$cs1_array[] = array(
    "item" => "superuser",
    "price" => "40.00"
);
$cs1_array[] = array(
    "item" => "serverfault",
    "price" => "20.00"
);
// and so on

作为上述代码的更简洁的替代方法,您可以创建数组并在单个语句中用值填充它:

$cs1_array = array(
    array(
        "item" => "stackoverflow",
        "price" => "30.00"
    ),
    array(
        "item" => "superuser",
        "price" => "40.00"
    ),
    array(
        "item" => "serverfault",
        "price" => "20.00"
    ),
    // and so on
);

然后foreach循环将正常工作:

if(sizeof($cs1_array) > 0){
    echo "<table>";
        foreach($cs1_array as $item){
        echo "<tr>";
        echo "<td>{$item['item']}</td><td>{$item['price']}</td>";
        echo "</tr>";
        }
    echo "</table>";
}