Array of associative arrays in PHP - php

I have a function to use but I don't know the content of this function. The only thing I know is that the function returns an array of associative arrays and the keys for the arrays. The data that the function returns come from a database. Can you help in how to read the data from this array? I am confused with the arrays. For now I am doing this:
$array = myfunction($var);
if(!empty($array))
{
while($row = mysql_fetch_array($array))
{
print"$row[elem1]
$row[elem2]";
}
}
I take the error: Warning: mysql_fetch_array() expects parameter 1 to be resource, array given in... I know that something is missing, but I till now I can't fix it.

If the function is returning an array then why are you using it in mysql_fetch_array. It is useless. Instead use this
foreach($array as $key => $value){
echo $key;
echo '<br>';
echo $value;
}
This will print the whole array.
Or a short method is
echo '<pre>';
print_r($array);
echo '</pre>';

Something like -
$array = myfunction($var);
foreach($array as $key => $row) {
print"{$row['elem1']} {$row['elem2']}";
}

You have to pass Resource Identifier to mysql_fetch_array() function.
Something like:
$sql = mysql_query('SELECT * FROM `table`');
if(!empty($array)) {
while($row = mysql_fetch_array($array)) {
print"$row[elem1]
$row[elem2]";
}
}

The error is correct .. the issue is not associative arrays in php but you are not using a valid mysql resource
Please see http://php.net/manual/en/function.mysql-fetch-array.php for documentation
Examples
$mysqli = new mysqli("localhost","root","","test");
$result = $mysqli->query("SELECT * FROM test");
$row = array() ;
echo "<pre>" ;
if($result->num_rows > 0)
{
while($row = $result->fetch_array(MYSQLI_NUM))
{
print implode (",", $row) . PHP_EOL;
}
}
Or
$array = myfunction($var);
if(!empty($array))
{
foreach($array as $key => $row)
{
if(is_array($row))
{
print implode (",", $row) . PHP_EOL;
}
else
{
print $row . PHP_EOL ;
}
}
}

Related

PHP show associative array content into JSON format

i'm new in PHP language. I'm writing a PHP script to get information from my online database(created on my altervista personal webpage) and convert in JSON format.
The problem is about when i get elements from my database i can show them correctly using "echo" command, but when i parse associative array to "json_encode" function i can't see correctly elements.
Here is the code:
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
foreach($row as $key => $value) {
echo "" . $key . ": " . $value;
echo "<br>";
$json_array[] = array(''=>$key, ''=>$value);
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
?>
The $result->fetch_assoc(); returns an associative array.
As i said before i can see correct information using echo commands.
The problem is when i use this:
$json_array[] = array(''=>$key, ''=>$value);
The output is as follow:
[{"":"Mark"},{"":"ABC"},{"":"25"}]
Basically it's showing me only the second parameter "=>$value", while the first parameter "=>$key" is ignored.
Can you tell me please what should i change in order to see also the first parameter in my output?
Thanks
The correct way would be to do that
$json_array[] = array( $key => $value );
instead of
$json_array[] = array(''=>$key, ''=>$value);
You are essentially adding an EMPTY string as key and the $key as value at first, and then you replace it with the $value as they share the EMPTY string key in the array.
Read more at: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.array-func
First param is ignored because it has the same key as the second (the key is ''), you should write:
$json_array[] = array($key, $value); // Indexed array
Output will be:
[["key1", "value1"],["key2", "value2"],["key3", "value3"]]
OR
$json_array[] = array($key => $value); // Associative array
Output will be:
[{"key1": "value1"},{"key2": "value2"},{"key3": "value3"}]
Try:
sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$json_array[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
In your code you are parsing only the first db result

Implode array in php mysql_fetch_array

I cannot solve this seeming simple problem. I have the following simple code and all I want is to echo the result of $ATL5_Alert_query and separated by a comma (,):
$ATL5_Alert_query = mysql_query("SELECT `Mobile` FROM `dbo_tech_name` WHERE `AlertLevel`= 1");
$dataset = array();
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data;
}
echo implode (",", $dataset);
However, I'm getting "Notice: Array to string conversion "...
In your code $data is array as well, so $dataset becomes an array of arrays, which you cannot concatenate. You should get the searched value by this:
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data['Mobile'];
}
or:
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data[0];
}
or:
while ($data = mysql_fetch_assoc($ATL5_Alert_query))
{
$dataset[] = $data['Mobile'];
}
If you however cannot change this, and already have your $dataset array, you can implode it like that:
echo implode(',', array_map(function($a){
return $a['Mobile'];
},$dataset));

Printing an array in php

Now I understand that you cant just use echo to print the contents of an array and you have to use foreach but for some reason this is not working. Any ideas?
$rows = $stmt->fetchAll();
foreach ($rows as $key=>$row)
{
echo "My value at $key is $row";
}
}
Output:
My value at 0 is ArrayMy value at 1 is ArrayMy value at 2 is Array
It appears you've fetched something from PDO using fetchAll.
This method returns an array of arrays (rows). The inner arrays have column_name => value elements. So for example if you retrieved the column 'firstName' and 'lastName', these values for the first record will be $rows[0]['firstName'] and $rows[0]['lastName'] respectivelly.
The proper way to do this would be:
$rows = $stmt->fetchAll();
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
echo "My $column value for row $key is $value\n";
}
}
Protip: Watch the parentheses alignment, this doesn't matter for correctness but makes the code more readable :)
Looks like a multi-dimensional array to me. Try var_dump or print_r
var_dump($rows);
print_r($rows);
$row is another array which can not be converted directly to string. You can use this function to check array content.
function d($data)
{
echo '<pre>';
print_r($data);
echo '</pre>';
}
d($stmt->fetchAll());
and better you do this (if you forgot to remove its calling doesn't harm your site)
define('ENVIRONMENT', 'development');
function d($data)
{
if(ENVIRONMENT == 'development')
{
echo '<pre>';
print_r($data);
echo '</pre>';
}
}
d($stmt->fetchAll());
Try this to debug the content of $row:
$rows = $stmt->fetchAll();
foreach ($rows as $key=>$row)
{
echo "First key: $key | ";
foreach($row as $subkey => $subrow)
{
echo "Subkey: $subkey | Value: $subrow <br />";
}
}
Addiotinally, it's important to use functions like var_dump(), print_r() and var_export(), they will prevent a lot of problems for you.
//<pre> tag will give you a well formatted version of var_dump
echo "<pre>";
var_dump($rows);
echo "</pre>";
//#parram $data-array,$d-if true then die by default it is false
//#author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can write like this..
$rows = $stmt->fetchAll();
foreach ($rows as $key=>$row) {
p($rows); // to use p function use above code for p() in your code
}

Echo values of arrays?

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);
}

Displaying an associative array in PHP

I am trying to build a function that extracts information from a database and inserts it into an associative array in PHP using mysql_fetch_assoc, and return the array so another function can display it. I need a way to display the returned assoc array. This should be a different function from the first one
print_r($array) will give nicely formatted (textually, not html) output.
If you just want information about what is in the array (for debugging purposes), you can use print_r($array) or var_dump($array), or var_export($array) to print it in PHP's array format.
If you want nicely formatted output, you might want to do something like:
<table border="1">
<?php
foreach($array as $name => $value) {
echo "<tr><th>".htmlspecialchars($name).
"</th><td>".htmlspecialchars($value)."</th></tr>";
}
?>
</table>
This will, as you might already see, print a nicely formatted table with the names in the left column and the values in the right column.
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $column => $value) {
//Column name is in $column, value in $value
//do displaying here
}
}
If this is a new program, consider using the mysqli extension instead.
Assuming you've made the call, and got $result back:
$array = new array();
while($row = mysql_fetch_assoc($result)){
$array[] = $row;
}
return $array;
This should get you going:
$rows = mysql_query("select * from whatever");
if ($rows) {
while ($record = mysql_fetch_array($rows)) {
echo $record["column1"];
echo $record["column2"];
// or you could just var_dump($record); to see what came back...
}
}
The following should work:
$rows = mysql_query("select * from whatever");
if ($rows) {
$header = true;
while ($record = mysql_fetch_assoc($rows)) {
if ($header) {
echo '<tr>';
foreach (array_keys($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
$header = false;
}
echo '<tr>';
foreach (array_values($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
}
}
(Yes, blatant mod of Fosco's code)
This should print the column headers once, then the contents after that. This would print just whatever columns were retrieved from the DB, regardless of the query.

Categories