php 7 put data from csv column into a set - php

I need to read a csv file and put all of the data in a particular column into a Set ( so as to eliminate duplicates ). I have earched through the questions here and I see some similar answers for arrays but I am not well enough versed in php to extrapolate from these examples to my use case.
Specifically, I need to grab a csv file of all the cars towed by the city of Chicago. Then I need to loop through the 'Make' column and grab all of the makes. I do not want to include duplicates so I'm thinking a Set ( which I understand php7 supports) would be an appropriate data structure.
I'm not concerned at all with efficiency at this point, more with simplicity as this is part of a homework assignment. I had the option of just manually going through and picking out the makes but thought that would be an easy out.
I guess array is ok since someone was kind enough to inform me about these two functions.
[code]
$towFileString = file_get_contents("put link here");
file_put_contents('tow-data.csv', $towFileString);
$file = fopen('tow-data.csv', 'rb');
$csvArray = array();
while(!feof($file)){
$csvArray = fgetcsv($file);
}
$allMakes = array_column($csvArray, 'Make');
$uniqueMakes = array_unique($allMakes);
When I run the program, however, PHP tells me this:
Warning: array_column() expects parameter 1 to be array, boolean given
So it is telling me that the array I just created is really a boolean.
I was hoping you could give me some insight into why this is the case
NOTE: I am not asking you to do my work for me. I'd just like a few pointers to get me started in the right direction.

You can put the values of the 'make' column into a seperate array using the array_column function, like this:
$allMakes = array_column($towedCars, 'make');
and then run array_unique on it, which will eliminate all the duplicates:
$uniqueMakes = array_unique($allMakes);

Related

Struggling to understand how this particular code works.

I am faced with a piece of code that does not make a lot of sense to me. I am working on a website using PHP and Smarty template, but there is one line of code regarding arrays that i do not understand how it works.
$SLang = &SLanguage::getInstance();
$q="SELECT * FROM texte where text_lang='{$SLang->lang}' ORDER BY text_id";
$texte = _sqlFetchQuery($q);
foreach($texte as $text)
{
$texteList[$text['text_alias']]['text'] = $text['text_text'];
if($text["text_category"]==3){
$philosophyList[] = $text["text_text"];
$philosophyListSeo[] = $text["text_alias"];
}
}
The output of "var_dump" on $philosophyList gets out only the "text_text" column from the database, and i do now understand the structure of how it gets there. Can someone care to explain? How does this particular line of code works? $texteList[$text['text_alias']]['text'] = $text['text_text'];
It's called a jagged array.
It's shorthand for this:
$texteList[$text['text_alias']] = array('text'=>$text['text_text']);
So it's creating a named array using whatever text is $text['text_alias'] brings out, and assigning as it's value an array with a named "text" element.
But this is irrelevant to $philosophyList[]. To understand how $philosophyList[] is working, you need to understand how foreach works; basically it takes each item in an array (in this case $texte) and assigns the value of that array item to a variable (in this case $text). This is just an easier way to do a for loop. They could just have easily done:
$philosophyList[] = $texte[$i]["text_text"];

How to merge some static data with json encode mysql array data?

I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.

Sort multi-dimensional array built from CSV data using PHP

Trying to sort an array in PHP that is being populated from a CSV. I would also, ideally, LOVE to be able to control the sort by clicking on tabs in the table here .. Right now, though, my first task at hand is just sorting the damn thing.. been working on this for over 3 days now.. any help is GREATLY appreciated!! Cheers!
PHP
<?php
$fp = fopen("https://spreadsheets.google.com/pub?key=0AjZgwY03sLMGdHVoWjhucGowWWJBb2g2NnQzVG9HZFE&hl=en&single=true&gid=0&output=csv","r");
$rows = array();
while (($row = fgetcsv($fp)) !== FALSE) {
$rows[] = $row;
}
fclose($fp);
$headers = array_shift($rows);
foreach ($rows as $row) : list($ShowKey, $ShowFeedURL, $ShowLink, $ShowIcon, $ShowTitle, $ShowTag, $ShowCategory, $ShowEps, $ShowLastUpdate, $ShowNew) = $row;
$oddpost = ( empty( $oddpost ) ) ? '_odd' : ''; ?>
I recently did this. I had a multi-dimensional array of records from a database, and I needed to sort them based off of one specific column in the array. Here's what I did:
foreach($TimeRecords as $key => $value)
{
$Rates[$key] = $value['rate'];
}
array_multisort($Rates, SORT_ASC, $TimeRecords);
I build an array of only the column I need, then I use the array_multisort() function to sort the array based off of that column.
You can write functions that will do this in PHP and then just call them with javascript ajax calls and reload that part of the page when it's done sorting.
Instead of sorting the table in PHP, you may consider doing it client-side in Javascript. For instance have a look at this jQuery plugin: http://tablesorter.com/
You may find usort() function helpful. It accepts callback argument, which may be used for sorting by specific field.
I had a similar issue to this today. Basically what I ended up doing is creating a temporary table which I loaded in the rows from the csv file that I needed. From there, I used php to sort and organize the data and update or add to the table I needed to alter.
Example, I made a table called 'temp' and loaded in all the rows of the category I needed. Then, once this was in the table, I made a php script which sorted the information by number of total sales in descending order. From there, I did a query to update my main table and used a limit to control this (only the top 200 items by number of sales).
It was very easy to do and hopefully it will help you or someone else.
Keep in mind. If you're going to do this more than once, you will need to truncate the temporary table to remove the old rows first.

How do I stop MySQL from duplicating every column's entry in returned arrays?

My MySQL queries are returning arrays with duplicate entries: numbered keys and labeled keys with the same data inside. This may be standard, but it seems like a waste, and something that could cause problems if I'm printing values. I mean, not a huge problem, obviously. But I'm just curious if I can stop that. It seems unnecessary. For example:
Array(
[0] => "Ted",
[first_name] => "Ted",
[1] => "Schmidlap",
[last_name] => "Schmidlap"
)
And so on.
I'm pretty new to a lot of this, so this may be a simple question, but Googling doesn't seem to have any answers for me. Anyone know the reason this happens? I'm using PHP's PDO now, but I was doing it straight through the MySQL functions before and the same thing was happening, so I assume it's a byproduct of MySQL interaction.
I can iterate through and unset the numeric ones, because I don't need them, but they're not really in the way right now, so that's just an extra step. Still, is there a way to simply not have them fetched in the first place?
Presumably this is happening after you use mysql_fetch_array (or similar).
You need to add in a flag to specify what array type you want returned or PHP assumes both.
i.e. mysql_fetch_array($result_set, MYSQL_ASSOC|MYSQL_NUM|MYSQL_BOTH)
That depends on the function you are using.
Some functions return both types, others return only one of them.
If you are using PDOStatement->fetch, notice the optional $fetch_style argument it takes.
Your issue is with the mysql_fetch_array function.
If you want only the numbers, use:
$row = mysql_fetch_array($result, MYSQL_NUM)
If you want only the text indexes, use:
$row = mysql_fetch_array($result, MYSQL_ASSOC)
I usually use MySQLi but for PDO you can find more information here: http://us3.php.net/manual/en/pdostatement.fetch.php
Which seems to mean that you should be using this for text indexes:
$row = $statement->fetch(PDO::FETCH_ASSOC);
And this for numeric indexes:
$row = $statement->fetch(PDO::FETCH_NUM);
Also, just to note this since it isn't listed here, if you want an associative array, you can use mysql_fetch_assoc(), or if you want an enumerated (numbered) array use mysql_fetch_row() instead of mysql_fetch_array(). I use this mostly because without it I would often forget the flag, so I got into the habit of just using the specific function.

PHP Change Array Over and Over

I have any array
$num_list = array(42=>'0',44=>'0',46=>'0',48=>'0',50=>'0',52=>'0',54=>'0',56=>'0',58=>'0',60=>'0');
and I want to change specific values as I go through a loop
while(list($pq, $oin) = mysql_fetch_row($result2)) {
$num_list[$oin] = $pq;
}
So I want to change like 58 to 403 rather then 0.
However I always end up getting just the last change and non of the earlier ones. So it always ends up being something like
0,0,0,0,0,0,0,0,0,403
rather then
14,19,0,24,603,249,0,0,0,403
How can I do this so it doesn't overwrite it?
Thanks
Well, you explicititly coded that each entry should be replaced with the values from the database (even with "0").
You could replace the values on non-zero-values only:
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if ($pq !== "0") $num_list[$oin] = $pq;
}
I don't get you more clear, i thought your asking this only. Check this
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if($oin==58) {
$num_list[$oin] = $pq;
}
}
In my simulated tests (although You are very scarce with information), Your code works well and produces the result that You want. Check the second query parameter, that You put into array - namely $pg, thats what You should get there 0,0,0,0,0...403 OR Other thing might be that Your $oin numbers are not present in $num_list keys.
I tested Your code with mysqli driver though, but resource extraction fetch_row is the same.
Bear in mind one more thing - if Your query record number is bigger than $numlist array, and $oin numbers are not unique, Your $numlist may be easily overwritten by the folowing data, also $numlist may get a lot more additional unwanted elements.
Always try to provide the wider context of Your problem, there could be many ways to solve that and help would arrive sooner.

Categories