Im stuck with this simple problem in php:
$words = array();
while ($allrow = mysqli_fetch_array($all))
{
$words = "".utf8_encode($allrow["eng"])."" => "".$allrow["id"]."";
}
foreach ($words[] as $key => $word) {
I wanna have an array with some words and its id. In the foreach loop I need to be able to know which id each word has.
You array building syntax is off, try this:
// array key is the id, swap if needed, but I assume the ids are unique
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
Every time you say $words = $anything
, you are overwriting the last iteration.
This should have generated a parse error:
."" => "".
Not sure how that slipped by your testing. No need for the empty ""
strings either.
Inside your foreach loop, add each entry to the array.
$words[utf8_encode($allrow["eng"])] = $allrow["id"];
if you actually want the id as the key, which is more probable, you reverse the assignment:
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
As well, you should not iterate using $words[]
. That does not make sense. Useforeach($words as $key => $value)
As assigning array values with []
and iterating arrays are basic concepts, you should study up on PHP arrays before trying to use them.
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);
and then in the foreach loop use foreach ($words as $key => $word) {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.