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.
Related
One of my PDO statements returns an array. For JSON encoding I want to cast this array to an Object and append it to another array.
while($row = $sth->fetch()){
foreach($row as $key=>$value){
$r = (object) $row;
$recordArray[] = $r;
}
}
$json->record = $recordArray;
echo json_encode($json);
$recordArray seems to stay empty but it doesn't if I write $recordArray[] = "test" in the loop. So there must be something wrong with my Object $r but I can't spot the mistake. Any help is appreciated.
Here is an easier way
echo json_encode(array('record'=>$sth->fetchAll(PDO::FETCH_OBJ)));
Your foreach is wrong: in body you use object on which you iterate.
May be you mean this?
$records = [];
while($row = $sth->fetch()) {
$current = [];
foreach($row as $key => $value) {
$current[$key] = $value;
}
$records[] = $current;
}
If I understood, you want to loop over $row and add every object within $row to $recordArray.
Then you should do this:
while($row = $sth->fetch()){
foreach($row as $value){
$recordArray[] = $value;
}
}
Is there any reason why this code would avoid the first value in an array?
$rappels = array();
$i = 0;
while($row = $result->fetch_assoc()) {
foreach($row as $key=>$val) {
$rappels[$i][$key] = $val;
}
$i++;
}
return $rappels;
When I return the rappels, it always seems to avoid returning the very first item, which should be [0] in the array.
You have a number of redundancies in your code. You don't need $i nor do you need the foreach loop.
$rappels = array();
while($row = $result->fetch_assoc()) {
$rappels[] = $row;
}
return $rappels;
Your code as you posted it shouldn't remove any rows. You may need to look at the code you haven't posted to see if there's something there that's skipping the first row.
I created associative array as below
$query = "SELECT word,meaning1,meaning2 FROM dictionary";
$results = $db->exeQuery($query);
$arrDictionary = array();
while($line = mysql_fetch_array($results, MYSQL_ASSOC))
{
$arrDictionary[] = $results;
}
Then i am iterative through another list of word array
foreach ($file_array as $value)
{
}
within this loop, for each word, i need to find meaning1 and meaning2. Tried many ways, but no success.
Could somebody help me?
I think
while($line = mysql_fetch_array($results, MYSQL_ASSOC))
{
$arrDictionary[] = $results;
}
should be replaced with
while($line = mysql_fetch_assoc($results))
{
$arrDictionary[] = $line;
}
and
foreach ($arrDictionary as $value)
{
echo $value['field_name'];
}
I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}
how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/