Two dimensional associative array in PHP - php

In my code I'm getting data (three columns) from a sql db and I want to store the rows in an associative PHP array. The array must be multi-dimensional because I want to use the row id from the database as a key so that i can fetch values like this:
$products["f84jjg"]["name"]
$products["245"]["code"]
I've tried using the following code but it doesn't work:
while ($row = mysql_fetch_row($sqlresult))
{
$products = array($row[0] => array(
name => $row[1],
code => $row[2]
)
);
}
Also, how should I reference the key if it is taken from a variable? What I want to do is:
$productName = $products[$thisProd]["name"];
Will this work?

This should do it, assuming row[0]'s contents is a unique identifier (else you could override a row):
while($row = mysql_fetch_row($sqlresult)) {
$products[$row[0]] = array(
'name' => $row[1],
'code' => $row[2]
);
}
You need to put quotes around the array keys, and you were creating an array of array of arrays.
Also note you could use mysql_fetch_assoc instead of mysql_fetch_row, which would give you the array keys as the column names, which would make this much easier/cleaner:
while($row = mysql_fetch_assoc($sqlresult)) {
$products[$row['myidcolumn']] = $row;
}
After you do this, the code you described would work.

Related

Why is array_unique not working in this situation

I have a column that contain integer values. I join all columns by doing
"SELECT GROUP_CONCAT(column) AS column"
Then I build an array doing
while ($row = $result->fetch_assoc()){
$employees[] = $row['column'];
}
print_r($employees) returns Array ( [0] => 1,2,3,4,68,25,1 )
So I want to remove the duplicate 1 and for that I use array_unique
print_r(array_unique($employees));
This still brings back Array ( [0] => 1,2,3,4,68,25,1 )
What am I doing wrong here
Solution at SQL side:
SELECT GROUP_CONCAT(DISTINCT column) AS column
if you want an ordered list:
SELECT DISTINCT column ORDER BY Column
and then store all rows by
while(...) $employees[] = $row['column'];
The problem is that you are trying to use array_unique() on a string, which won't really do anything.
You can break this string into an array by using the explode() function.
$unique = array_unique(explode(',', $employees[0]);
Alternatively, you could just check inside your loop if a value has already been put into an array using in_array().
while ($row = $result->fetch_assoc()){
if(!in_array($row['column'], $employees)) {
$employees[] = $row['column'];
}
}
Just use the array_map function. And map all value with intdiv function
$employees = array_unique(array_map("intdiv", $employees));
print_r($employees);

getting correct json response

I am getting data from database and showing it in form of json
Here is how I do:
while ($row = #mysqli_fetch_row($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode($result1,true);
which gives result in this form
[["29"],["13702210"],["892344"],["Multi AxleB9RVolvo"],["10:30AM"],["06:45PM"],["14"],["37"],["650"]]
This prints only the database value fetching from table. But this response marked as invalid json response
Each of the fields has name in table.
I want to see json response in this form:;
{"routes":[{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}},{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}},{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}}]}
This contains name and nested preview. How can I do this?
I don't know the strucutre of your database, but:
while ($row = #mysqli_fetch_assoc($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode(array('routes' => $result1));
May give you the result you want. mysql_fetch_assoc() returns the table rows as associative arrays which will provide keys.
Then array('routes' => $result1) creates a new associative array with the key 'routes' matching your index of arrays.
If they keys aren't correct in your sql response you could try using select field_name as alias_name in your SQL query to return the appropriate field names.
The real trick here is setting up associative arrays with appropriate keys for each value so that json_encode creates objects rather than lists.
You need to use associative array, use this;
while ($row = #mysqli_fetch_assoc($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode($result1,true);
// for `routes` parent
// echo $result1 = json_encode(array("routes" => $result1));

$row['column'] in PHP

Hello guys I have seen a code with $row['columnname'].The code is
$myQuery = "SELECT * FROM information_schema.columns WHERE table_name = '$tabname'";
$re = mysql_query($myQuery);
while($row = mysql_fetch_array ($re)){
if(!empty ($row)){
$col_name = $row['COLUMN_NAME'];
$myQuery = "SELECT ".$col_name." FROM ".$tabname." WHERE sampleid='".$sid."'";
echo "<br>".$myQuery;
$reqq = mysql_query($myQuery);
$roww = mysql_fetch_array($reqq);
echo "<br>".$roww[$col_name];
}
}
My question is what is the use of $row[] in php?
Is it used to embed the column value like $row['columnname'] or just adding a variable like $row[$anyvariable].
That is called bracket notation. $row is an array, which has properties. In this case, it has named properties, so it is an associative array. An associate array has key/value pairs. It looks like this:
$myArray = [
'key' => 'value'
];
To echo the value of the property above, you would use echo $myArray['key'];
In the specific code you included, the property name is "COLUMN_NAME" and it has a value. The code assigns that value to the variable $col_name.
Here's another sample usage to help clarify all of this:
$people = [
'Susan' => [
'Age' => 24,
'Phone' => '555-123-4567'
],
'Jack' => [
'Age' => 27,
'Phone' => '555-9876-5432'
]
];
echo $people['Jack']['Age']; // 27
while($row = mysql_fetch_array ($re)){
This statement loops over all the rows returned in your result set $re and while looping, on every iteration you will get the current row as an array in your variable named $row, this name can be anything, it doesn't have to be $row necessarily.
Then
$col_name = $row['COLUMN_NAME'];
Is just reading $row as an array and picking up the value for the key COLUMN_NAME. This will be one of the columns that were returned by your query for each row of the result set. This also can be any name depending upon your query.
it is from mysql_fetch_array
it returns result array if your query/result was found, if not just FALSE instead
Like it says on the PHP site :
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
It's not variables that would go inside the $row[] , it's the column name that you have called in your SELECT query .
In your case, you have a SELECT query to return all the columns of a table. 'COLUMN_NAME' is in fact really the name of a column in the table of information_schema.column
mysql_fetch_array returns an array,
$row = [
'column_name' => 'column_value'
]
so the statement
$row = mysql_fetch_array ($re))
will fetches the column names from information_schema.columns that will be stored into $col_name.
$col_name = $row['COLUMN_NAME'];
for more read mysql_fetch_array

php export sqlite table to csv

I'm trying to export a table to a CSV file using php and it's working with the following code:
while($row = $results->fetchArray()) {
print '"' . stripslashes(implode('","',$row)) . "\"\n";
}
However, it creates duplicates of each field when I view the CSV file. I don't know how to limit them down to one per field.
This is because SQLite3Result::fetchArray by default fetches both a numeric and a named index for each column in the result. So $row might look like this:
array(
0 => 'Fred',
'firstname' => 'Fred',
1 => 'Jones',
'lastname' => 'Jones',
2 => 'fredjones#example.com',
'email' => 'fredjones#example.com'
)
The way around this is to specify other behaviour in the fetchArray call by passing a constant:
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
This means that only the names of the columns will be fetched. Equally, you could do SQLITE3_NUM: in your case it would make no difference.
Note also that a nicer way to output CSV data is with the fputcsv method, which handles enclosure and escaping as necessary. It requires a file handle: if you just want to echo the data, you can use the STDOUT constant:
fputcsv(STDOUT, $row);
Running example
fetchArray returns both associative and numeric indices by default. To return only numeric indices use:
while($row = $results->fetchArray( SQLITE3_NUM )) {
Or to return an associative array use:
while($row = $results->fetchArray( SQLITE3_ASSOC )) {

PHP multidimensional array from database results

I'm a bit new to multidimensional arrays, and would like to see if I'm doing it right. preferably, I'd like to name the arrays within the main array for ease of use.
$unique_array = array(
username=>array(),
user_id=>array(),
weeknumber=>array()
);
and then I have a while loop which checks some database results:
while($row = mysql_fetch_array($query)) //yes, I know mysql is deprecated
{
$unique_array[] = username=>$row['username'], user_id=>$row['user_id'], week number=>['weeknumber'];
}
I'm not sure if I am placing the values in the array from within the while loop correctly, or if it needs to be done some other way. I couldn't find any resources I could easily understand on SO or elsewhere to deal with query results within a named array within a multidimensional array.
EDIT FOLLOW UP QUESTION: I also need to check the array for duplicate values, because there will be multiple values that are exactly the same, but I only want one of them.
Any help is appreciated!
EDIT SOLUTION:
By modifying the answer I was able to create code to fit my needs.
Array initialization:
$unique_array = array(
'username'=>array(),
'user_id'=>array(),
'weeknumber'=>array()
);
Building the array from within a while loop:
while($row = mysql_fetch_array($query))
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'weeknumber'=>$row['weeknumber']);
}
And finally, I need to make sure the array values are unique (there are duplicates entries as a result of database and query limitations), after the while loop I have:
print_r(multi_unique($unique_array));
Is the top level an associative array or a numeric array?
If it is an associative array, it should have structure like this:
$unique_array = array(
'username'=>array('John','Mike',...),
'user_id'=>array(1,2,3,...),
'week_number'=>array(1,2,3,...)
);
Or if it is a numeric array, it should have structure like this:
$unique_array = array(
array('username'=>'John', 'user_id'=>1, 'week_number'=>1),
array('username'=>'Mike', 'user_id'=>2, 'week_number'=>2),
array('username'=>'Sam', 'user_id'=>3, 'week_number'=>3),
...
)
for the first type use the code below:
while ($row = mysql_fetch_assoc($query)) {
$unique_array['username'][] = $row['username'],
$unique_array['user_id'][] = $row['user_id'],
$unique_array['week_number'][] = $row['week_number'],
}
for the second type, it is something like your code. But there are some syntax problems:
while($row = mysql_fetch_array($query)) //yes, I know mysql is deprecated
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'week_number'=>$row['weeknumber']);
}

Categories