Array ( [0] => Array ... problems extracting array values - php

I am trying to run a function that gets information from a DB and returns an array of the values, so I can then extract it on the page.
Inside the function, after my query I have the following code:
$example_array = array();
while ($row = mysql_fetch_assoc($query) {
$example_array[] = $row;
}
return $example_array;
And there ends my function. Outside of it, I have this:
extract($example_array);
And I would assume I could then directly echo any of the variables that were previously in $example_array, e.g. <?= $example_var ?> but they do not contain any data.
Running print_r($example_array); gives an array that looks like this:
Array ( [0] => Array ( [example_var] => Example String ) )
The start of that code makes me think my array is somehow "lost" inside another array's first ([0]) value, and as such is not extracting correctly.
Have I gone about adding data to that initial $example_array incorrectly?

When you do $example_array[] = $row;, you assign the current row to a new index of $example_array. If you want to access it like $example_array['row_name'], you'd have to assign it like this:
$example_array = $row;
But when you do this, $example_array will be overwritten until it has reached the last row (which means that $example_array will always contain the last row from the query). If you just want the first row, you can do this and skip the whole while loop:
$example_array = mysql_fetch_assoc($query);

Maybe :
$example_array = array();
while ($row = mysql_fetch_assoc($query) {
array_push($example_array, $row['exemple_var']);
}
return $example_array;

The issue is that mysql_fetch_array would have meant $row['row_name'] was valid.
As you added $row to the array $example_array, you now need to access it via it's array id too, such as;
$example_array[0]['row_name'], $example_array[1]['row_name'] etc.
What exactly are you trying to achieve? May be easier to offer assistance if we know.

Related

Add values into same array key

I'm sure this is a silly question, but I don't understand the reason. Why I cannot add values into the same array key? The values were overwritten.
$rows=array();
while($row = mysqli_fetch_array($result)) {
$rows[strval($row['year'])]=array('month'=>$row['month'],'satisfaction'=>$row['sat_per_month']);
}
For now I'm assuming you want a multidimensional array with the year and inside each row with the month and satisfaction as array. You just have to append it by using $rows[strval($row['year']][], since each array key is unique and you will just overwrite it currently.
So your code would look like:
$rows=array();
while($row = mysqli_fetch_array($result)) {
$rows[strval($row['year'])][] = array('month'=>$row['month'],'satisfaction'=>$row['sat_per_month']);
}
In PHP (and almost all programming languages) array indexes are unique. This means that $arr["teletubbies"] cannot be "lala" and "noonoo" at the same time. This is for the simple reason that if you would call $arr["teletubbies"] at a later time PHP cannot know whether you meant "lala" or "noonoo" then.
To solve this issue (you want some things ordered by their year, e.g. 2014) it is advisable to make the value correlated to key 2014 a new array, thus creating a multidimensional array. You seem to understand that, but your implementation is wrong, as you are now just changing $rows[strval($row['year'])] to something new instead of appending the new values.
There are multiple solutions to this problem to do so:
Solution 1:
$rows=array();
while($row = mysqli_fetch_array($result)) {
//The syntax [] means: insert after the last defined key, more information at: http://php.net/manual/en/language.types.array.php look for $arr[] = 56;
$rows[strval($row['year'])][] = array('month'=>$row['month'],'satisfaction'=>$row['sat_per_month']);
}
Solution 2:
$rows=array();
while($row = mysqli_fetch_array($result)) {
//Make sure $rows[strval($row['year'])] is an array
if (!isset($rows[strval($row['year'])])) $rows[strval($row['year'])] = Array();
//array_push pushes a new array element to the last element of an array, documentation here: http://php.net/manual/en/function.array-push.php
array_push($rows[strval($row['year'])],array('month'=>$row['month'],'satisfaction'=>$row['sat_per_month']));
}
There are probably several other solutions aswell, but you get the idea.
To call one of the $rows[strval($row['year'])] later, you must make sure you call the newly created indexes! For example:
//Three indexes! 1st is the year, 2nd is the nth child you added and third is Array("month" => "..", "satisfaction" => "...");
print_r($rows["2014"][5]);
or
echo $rows["2014"][3]["month"]." ".$rows["2014"][3]["satisfaction"];
Array index is unique. The code below should work for your case.
$rows=array();
while($row = mysqli_fetch_array($result)) {
$rows[strval($row['year'])][] = array('month'=>$row['month'],'satisfaction'=>$row['sat_per_month']);
}
hope I understood your question correctly. One array key can store only one value (or one array of values) so:
$array[$key] = $value; //will overwrite what is under that key
$array[$key][] = $value //will add a value as a new sub-array node resulting in:
array(
'key' => array (
'0' => 'value',
),
)

Breaking a MultiDimensional Array into a Single Dimension

I have fields in mySQL which is currently being stored like this under the field "tags"
Shopping|Health & Beauty
Coffee|Shopping
What I'm trying to do is to loop through this to create a single dimension array and to grab only the unique values.
I have my query selecting DISTINCT tags from TABLE and run the loop like this:
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
}
echo "<pre>";
print_r($imploded_tags);
The result from the print_r is showing it as a multidimensional array. I've tried to reexplode it and implode it in different ways, but I haven't been able to get any success. Is there a way that I can create this into a single dimension array? Not all tags will have an equal amount of tags separated by |, so I can't seem to get it to go with a function that I tried from another StackOverflow post. Any help would be greatly appreciated!
OUTPUT:
Array
(
[0] => Array
(
[0] => Shopping
[1] => Health & Beauty
)
[1] => Array
(
[0] => Coffee
[1] => Shopping
)
try this
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$tags = explode("|",$tags);
foreach($tags as $v){
$imploded_tags[] = $v;
}
}
I would do something like:
$imploded_tags = array_merge(explode("|",$tags), $imploded_tags);
}
$imploded_tags = array_unique($imploded_tags);
echo "<pre>";
print_r($imploded_tags);
See the manual on array_merge and array_unique.
However, I do think you are not using the right way to store your tags; they should be stored in a separate table as separate values.
What's going on is when you're fetching your rows from MySQL, you're essentially getting a bunch of data in an array in the first place, which is why you have to loop through them.
With your your implode function, you're taking a bunch of strings, then getting another array set and then appending that to an external array.
If you really wanted to get a single dimensional array without having this multidimensional thing going on, all you really need to do is utilize another loop within that loop.
$all_tags = array();
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
for($i = 0; $i < count($imploded_tags); $i++) {
$all_tags[] = $imploded_tags[$i]
}
}
print_r($all_tags);

Storing array within an array using PHP

foreach ($topicarray as $key=>$value){
$files = mysql_query("mysqlquery");
while($file = mysql_fetch_array($files)){ extract($file);
$topicarray[$value] = array( array($id=>$title)
);
}
}
The first foreach loop is providing me with an array of unique values which forms a 1-dimensional array.
The while loop is intended to store another array of values inside the 1-dimensional array.
When the while loop returns to the beginning, it is overwriting it. So I only ever get the last returned set of values in the array.
My array ends up being a two dimensional array with only one value in each of the inner arrays.
Feels like I'm missing something very basic here - like a function or syntax which prevents the array from overwriting itself but instead, adds to the array.
Any ideas?
Step 1. Replace $topicarray[$value] with $topicarray[$value][]
Step 2. ???
Step 3. Profit
Make $topicarray[$value] an array of rows, instead of one row. Also, don't use extract here.
foreach ($topicarray as $key => $value) {
$rows = array();
$files = mysql_query("mysqlquery");
while($file = mysql_fetch_array($files)) {
$rows[] = array($file['id'] => $file['title']);
}
$topicarray[$value] = $rows;
}
Also, you should switch to PDO or MySQLi.

PHP Array from MySQL is not empty but has an empty entry - how to avoid

I am trying to check whether an entry exists (one or more) in our database. However, even when I know there are no entries, I am getting an array which has a first entry of zero. Therefore it is not empty and I am not getting what I need.
Here's my code:
<?php
$query = mysql_query("SELECT * FROM table WHERE column = $yfbid_number AND timestamp BETWEEN (NOW()- Interval 1 DAY) AND NOW()");
$array[] = array();
while ($row = mysql_fetch_assoc($query)){
$array[] = $row['column'];
}
?>
When doing print_r on an array which should be empty, I am getting: ( [0] => Array ( ) ) and therefore count is 1 and not zero, which messes up my code. Any ideas how to get to a truly empty array in this situation?
I'd rather not delete this entry but avoid it in the first place, because in most use cases I will get either an empty array or one that only has one entry (a real entry), in which case I will want to easily distinguish between the two. (as it is now, both give a count of 1 entry, which is very bad for our porpuses). Thanks.
Change:
$array[] = array();
to
$array = array();
With your version, if $array doesn't already exist, PHP will first create an array, then append an empty array to it. So you end up with a 1 element array whose only member is an empty array.
$array[] = array(); should be $array = array(). Right now, you are appending an array element to an array that is initialized. Turn notices on and you'll get a complaint about an undefined variable (probably).
I suggest you first do a SELECT COUNT(*) to determine how many entries you'll get. Then you KNOW that the result will be a useful answer, and can make or not make a subsequent query on the basis of your result.

Looping though a while statement

I have a sequence of mysql query result resources stored in a array.
E.G array([0] => resource [1] => resource ...ect);
This code retrieves the first resource in the array:
$third_count = "0";
while ($user_result = mysql_fetch_array($user[$third_count])) {
print_r($user_result);
}
$third_count = $third_count +1;
I'm just stuck trying to find an if statement that'll loop though the array.
Something like: while ($third_count =< $second_count) is what I need, but it doesn't seem to work.
Where $second count is the number of elements in the array.
Thanks for pointers!
What you want to do is use a foreach loop to loop through that array of result resources. Counts will not matter then.
foreach($resourcearr as $res) {
while ($user_result = mysql_fetch_array($res)) {
print_r($user_result);
}
}

Categories