开发者

What is the problem with this foreach loop?

开发者 https://www.devze.com 2023-03-16 20:33 出处:网络
why doesnt this array work? What do I do wrong? The result of my foreach loop is always either empty or just some weird numbers and signs. So what is wrong with my foreach loop?

why doesnt this array work? What do I do wrong? The result of my foreach loop is always either empty or just some weird numbers and signs. So what is wrong with my foreach loop?

$array = array();

while($row = mysqli_fetch_开发者_运维百科array($result)) {
    if(!empty($row["some"])) {
        $array["some"] = $row["some"];
        $array["some2"] = $row["some2"];
    }

}
foreach($array as $property=>$value) {
echo '<p>'.$value["some"].' - '.$value["some2"].'</p>'; }


$array will have only two properties, some and some2. Therefore your foreach loop doesn't make any sense. The foreach will loop two times, the first time with this:

$property = 'some';
$value = $row["some"];

and the second with this:

$property = 'some2';
$value = $row["some2"];

You will have to make $array multidimensional in your first loop by doing this:

while($row = mysqli_fetch_array($result)) {
    $new = array();
    if(!empty($row["some"])) {
        $new["some"] = $row["some"];
        $new["some2"] = $row["some2"];
        $array[] = $new;
    }
}

or shorter:

while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array[] = array('some' => $row["some"],
                         'some2' => $row["some2"]);
    }
}


$array["some"] and $array["some2"] are specific array elements. You are overwriting them every iteration of your while loop.

Not sure what you're trying to actually accomplish but I think possibly this is what you want:

$array = array();

while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array["some"][] = $row["some"];
        $array["some2"][] = $row["some2"];
    }

}
foreach($array["some"] as $property=>$value) {
  echo '<p>'.$value.' - '.$array["some2"][$property].'</p>'; 
}

or

$array = array();

while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array[] = array('some' => $row["some"],
                         'some2' => $row["some2"]);
    }

}
foreach($array as $property=>$value) {
  echo '<p>'.$value['some'].' - '.$value['some2'].'</p>'; 
}

or similar...kinda depends on what you're ultimately trying to accomplish...


This doesn't explain the weird numbers and signs, but you are overwriting $array['some'] and $array['some2'] on each loop iteration.

Instead, try this:

while($row = mysqli_fetch_array($result)) {
    if(!empty($row["some"])) {
        $array[] = array("some"=>$row['some'], "some2"=>$row['some2']);
    }
}


$array[] = array('some' => $row["some"], 'some2' => $row["some2"]);

But it would be better to retrieve only these columns.


Emil has the right answer :D. I love how people post so fast on here lol.

0

精彩评论

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