How to remove numbers from an 2d array php - php

I've got an 2d array that stores data from my database table then puts it in a json file. And since I'm not calling my column names because it is dynamic, the array is adding it's incrementation (numbers) automatically with the table cell detail, I don't want this.
Here is the json file example
{"0":"1","Fix":"1","1":"Sunday, May 11, 2014","Date":"Sunday, May 11, 2014","2":"FT","Time":"FT","3":"Cardiff City","Home":"Cardiff City","4":"1-2","Score":"1-2","5":"Chelsea","Away":"Chelsea","6":"Cardiff City Stadium (27,716)","Stadium":"Cardiff City Stadium (27,716)"}
I attempted to remove it in php like this
//Select everything in table
$query = mysql_query("SELECT * FROM ".$tablename);
//Storing the data into one arrays witk the ey => value
while($r=mysql_fetch_array($query)){
//Store the data as a 2d array
$json[] = $r;
}
foreach ($json as $key => $value) {
# code...
if(preg_match('/[0-9]/', $key)){
unset($json[$key]);
}else{
}
}
//Display the JSOn data
$o = fopen($tablename.'.json', 'w');
echo fwrite($o, json_encode($json));
fclose($o);

use MYSQL_ASSOC as a second parameter of the mysql_fetch_array() function.

Related

Illegal string offset 'Name' Error

I am trying to access the name field in the database through this code. But everytime it gives me "Illegal string offset error". I don't know the correct syntax needed inside second bracket of product_array.
$qry = "SELECT * FROM Products ORDER BY Product_Id ASC";
$result = mysqli_query($con,$qry);
$product_array = (array) $result->fetch_assoc();
mysqli_close($con);
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
echo $product_array[$key]['Name'];
}
}
?>
fetch_assoc() only fetches one row - iterating this row gives you column values (single string, number, ...). And you try to access Name index on such value, which leads to error.
You need to use $product_array = $result->fetch_all(MYSQLI_ASSOC); to get iterate all results.
Also instead of $product_array[$key]['Name'] you can use $value['Name'].
mysqli::fetch_assoc does not return a multi dimensional array rather a 2d row from the database (only one), so, if you have the following fields / data for example;
name abc
date 01-01-2018
Using a query and fecth_assoc will return an array such as;
[ 'name' => 'abc', 'date' => '01-01-2018' ]
So, using foreach, you can do the following;
foreach ($product_array as $key => $value)
{
// Example printing; name = abc
echo "{$key} = {$value}";
// Example prining; abc
echo $product_array[$key];
}

Foreach loop from array and how to contain it

I've been struggling with this problem for a week now and i don't have any more option but to ask a question here in stackoverflow.
I'm currently using PHP Spout for reading rows of a xlsx file and the array looks like this
Array
(
[Name] => abcd1234
[Address] => abcd1234
[Number] => abcd1234
)
Array
(
[Name] => abcd1234
[Address] => abcd1234
[Number] => abcd1234
)
Array
(
[Name] => abcd1234
[Address] => abcd1234
[Number] => abcd1234
)
The foreach loop looks like this
// Number of sheet in excel file
foreach ($reader->getSheetIterator() as $sheet) {
// Number of Rows in Excel sheet
foreach ($sheet->getRowIterator() as $row) {
// It reads data after header. In the my excel sheet,
// header is in the first row.
if ($count1 > 1) {
// Data of excel sheet
$data['Name'] = $row[0];
$data['Address'] = $row[1];
$data['Number'] = $row[2];
//Here, You can insert data into database.
//print_r($data);
//$sql = mysqli_query($connection, "INSERT INTO address(Name, Address, Number) VALUES ('$row[0]', '$row[1]', '$row[2]')");
foreach ($data as $key => $value) {
$value = trim($value);
if (empty($value)){
echo $output = "Row ".$count1." Column ".$key." is empty <br/>";
}
}
}
$count1++;
}
}
I have a problem where i need to loop all arrays and find the missing rows on each columns which i manage to do and now i need to ignore or count the duplicate values on rows. I tried doing array_unique but it did not work on the array i was using.
I also tried to insert my array into another array but i also had problems inserting into. I probably have issues with declaring my array but i'm still having some problems. How do i ignore the duplicates on multiple different arrays or how do i merge all the separate arrays into one array inside a foreach loop? Sorry i'm kinda new to arrays in php and thank you if someone is reading this.
Edit: The output that i was aiming for is to count the number of missing values inside an array/row from the xlsx file. Which is just like on the foreach loop in the example code. Example:
Row 213 Column Name is empty
Row 214 Column Name is empty
Row 214 Column Address is empty
This is what it looks like when i echo the missing values on rows from a xlsx file.
Now i need to validate if the xlsx file has duplicate rows. My first initial idea was to either echo rows with duplicate values i.e
Row 213 Column Name is has duplicates
Row 214 Column Name is has duplicates
Row 214 Column Address is empty
But everything got complicated which led me to try and use array_unique but also had problems because the way the array is being presented by the xlsx file.
As suggested in a comment on your question, use prepared statements.
As for a solution to your problem, when the SQL query executed and inserts the data successfully, add the unique identifier to an array. Before inserting new data into the database, check to see if the unique identifier is already in the array of inserted values. I'm on my phone, otherwise I'd provide an example. But that should help.
I hope this will get you going:
$data = array();
foreach ($sheet->getRowIterator($startRow = 2) as $row) {
$data[] = array('Name' => $row[0], 'Address' => $row[1], 'Number' => $row[2])
}
$names = array_column($data, 'Name');
$addresses = array_column($data, 'Address');
$numbers = array_column($data, 'Number');
$unique_names = array_unique($names);
$unique_addresses = array_unique($addresses);
$unique_numbers = array_unique($numbers);
$dup_names = array_diff($names, $unique_names);
$dup_addresses = array_diff($names, $unique_addresses);
$dup_numbers = array_diff($names, $unique_numbers);
And once you get to inserting into your database, here's how you use a prepared statement:
$stmt = $connection->prepare("INSERT INTO address(Name, Address, Number) VALUES (?, ?, ?)");
foreach ($data as $row) {
$stmt->bind_param('sss', $row['Name'], $row['Address'], $row['Number']);
$stmt->execute();
}

column counterpart to mysql_fetch_array() in PHP

I am new to PHP and looking for some help.
I read a column of data from a table in a database and send the data to a dropdown menu in the form of an array.
Now, the function mysql_fetch_array() converts a row of data into an array. I tried using the same function on a column with improper results.
Is there a function that similarly converts a column of data into an array?
You could simple iterate over the result(-rows) and get your column array if you like:
$columnArrays = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
foreach ($row AS $key=>$value){
if (isset($columnArrays[$key]))
$columnArrays[$key][] = $value; //add to existing array
else
$columnArrays[$key] = array($value); //create new array
}
}
Now you have all ids (depending on the column name) in $columnArrays["id"] - all names in $columnArrays["name"] and so on.

Looping through resultings record and getting duplicates in foreach

So I am trying what I feel is a simply loop through a record result. My query returns one row of data. I am attempting to simply pull the value of each row from the returning record into a variable called $questions. However, my var $questions when printed out has duplicates in every space. It should read something like Bob|Ted|Joe|Sally and instead it is reading Bob|Bob|Ted|Ted|Joe|Joe|Sally|Sally. Why is the code below running twice in the foreach loop?
while ($row = mssql_fetch_array($result)){
foreach ($row as $col => $value) {
$questions.=$value."|";
}
}
echo "Questions: ".$questions."<br/>";
Here is all you need to do:
$questions = "";
while ($row = mssql_fetch_array($result)){
$questions .= $row['fieldName']."|";
}
echo "Questions: ".$questions."<br/>";
The foreach() in addition to the while() is unnecessary.
The mssql_fetch_array according to PHP doc:
In addition to storing the data in the numeric indices of the result
array, it also stores the data in associative indices, using the field
names as keys.
The result includes a normal array [0...n] with one element for each column, but also an associative array where each value is represented by a key named after the column name.
So if your first column is Id, you could get id from a row in two ways:
$id = $row[0];
# or you could do this
$id = $row['Id'];
This is why you get each value twice when looping through row.

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

Categories