Displaying data from a CSV file with multi-dimensional PHP array - php

I'm trying to pull data from a CSV file that contains vehicle make, model, mileage etc...
Using this example from php -
<?php
$csv = array_map('str_getcsv', file('csv/csvin.csv'));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv);
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<div id='car'>".$key.":".$value."</div></br>";
}
}
?>
This is the array I get -
BodyStyle:"Station Wagon"
"DaysInStock":"27"
"Make":"Toyota"
"Model":"Prius v"
"MSRP":"0"
"SellingPrice":"26995"
"StockNumber":"387515"
"Trim":"Three"
"VIN":"JTDZN3EU9E3306528"
"Year" :"2014"
Now when I attempt to manipulate it or pull any individual values I simply cannot. How would I go about displaying this information with HTML tags for each value?
I have tried this:
print_r ($csv[0]['Make'];
echo $csv[0]['Make'];
Just to try and display a value but still nothing. I noticed for some reason the "BodyStyle" doesn't contain quotes like the rest so something definitely seems fishy.
From here how would I strip the quotes and break out each value?
This is the error being thrown -
Invalid argument supplied for foreach() in
Thanks in advance!

foreach($csv as $car){
echo "<tr><td>Make:</td><td>".$car['Make']."</td></tr>";
}
alternatively:
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<tr><td>".$key."</td><td>".$value."</td></tr>";
}
}
alternatively:
echo $csv[0]['Make'];

Try this one :
print_r ($csv[0]['Make']);
Basically the $csv variable is an array, to get its values you have to use the loop function, something like :
foreach ($csv as $data) {
foreach ($data as $index => $value) {
if ($index == "make") {
echo $value;
}
}
}
If you notice it a bit, the outer array is called indexed array (array with indexes) and to traverse the values use foreach ($csv as $data), while the inner array is called associative array (this array does not use number as index, but a name), and to traverse it use foreach ($data as $index => $value).
Try it and you'll see :)
PS: Sorry I didn't notice the inner array, for this case Richard's answer is the correct one. I have added a credit to his answer for giving a correct answer.

So I figured out that I only need 1 foreach loop like so -
foreach($csv as $car){
$type = $car[0];
$echo $type;
}
Works now and thanks all for the help!

Related

foreach $key variable clarification

I have this code
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key) {
$input = implode(",", $key);
}
} /*end is isset $_POST['submit2'] */
echo $input;
it produces the error " implode(): Invalid arguments passed " when I change the implode arguments to implode(",", $_POST['check_list']) it works as intended.
Can someone clarify why? As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?
Sorry if it's a silly question, I'm self taught and sometimes details like that are hard to find online.
You seem confused at several levels, so let me clarify some of them:
You said 'As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?'. The answers are NO and NO:
The $key variable outside the foreach loop will contain the last element of the array that's stored in $_POST['check_list'], $_POST['submit2'] seems to be only used to check if is set and nothing else in your piece of code. What foreach does is to traverse any iterator variable (an array in your case) and set the current item in a variable ($key) in your case. So after the loop, $key will contain the last element of that array. For more information refer to the docs: [http://php.net/manual/en/control-structures.foreach.php]
implode expects the second parameter to be an array, it seems you're not providing an array, but any other type. Is the last item of $_POST['check_list'] actually an array?
If you're trying to 'glue' together all items of $_POST['check_list'], you don't need to iterate, you just use implode on that one: $input = implode(",", $_POST['check_list']);. Otherwise, i'm not sure what are you trying to do.
Maybe if you explain what are you trying to do, we can help better.
Foreach already iterates trough your values. You can either get the value and echo it from there or you can add it to another array input if thats what you need:
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key => $value) {
$input[] = 'Value #'. $key .' is ' . $value;
}
}
echo implode(",", $input);
You are saying that $_POST['check_list'] is an array if implode() works on it, so no need to loop to get individual items. To implode() the values:
echo implode(',', $_POST['check_list']);
To implode() the keys:
echo implode(',', array_keys($_POST['check_list']));
foreach() iterates over an array to expose each item and get the individual values and optionally keys one at a time:
foreach($_POST['check_list'] as $key => $val) {
echo "$key = $value<br />";
}
implode function needs array as second argument. You are passing string value as second argument. That's why it's not working.

PHP foreach insert array

I have an array of arrays, and I am trying to foreach loop through and insert new item into the sub arrays.
take a look below
$newarray = array(
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
);
foreach($newarray as $item){
$item["total"] = 9;
}
echo "<br>";
print_r($newarray);
The result just give me the original array without the new "total". Why ?
Because $item is not a reference of $newarray[$loop_index]:
foreach($newarray as $loop_index => $item){
$newarray[$loop_index]["total"] = 9;
}
The foreach() statement gives $item as an array: Not as the real value (consuming array). That meaning it can be read but not changed unless you then overwrite the consuming array.
You could use the for() and loop through like this: see demo.
Note: This goes all the way back to scopes, you should look into that.

can we skip/jump in array while displaying PHP

I have a multidimensional array returned by drupal render function in that array i want to choose some last values
for example
$array['static_name'][number]['changes_every_time']['some_name']['value_i_need'];
is there ant way we can skip the "changes_every_time" level while printing array
is there a way we can use wild character in there
like if i want to print
echo $array['static_name'][number][*]['some_name'][value_i_need];
some thing like this
Store answer "no".
But what you can do is do a foreach over the keys of $array['static_name'][number]
foreach($array['static_name'][number] as $val) {
echo $val['some_name'][value_i_need];
}
This way you don't have to care.
well, you cold iterate the array at that "level" with a foreach loop
Untested code:
foreach ($array['static_name'][number] as $key => $value) {
echo $value['some_name'][value_i_need];
}

Updating and Sorting a Multidimensional PHP Array

I have a mySQL query that dumps into an array, is sorted and then displayed, and that works perfectly.
My problem is that I want to update these values, re-sort them and display. I've been able to update the values, but it's within the same for loop and so it doesn't re-sort. So then I close the loop and re-sort but it doesn't save the updates I made in the first loop. Help is much appreciated.
foreach ($arr as $mks){
if ($mks['Column1']==$Var) {$mks['Column2'] = $mks['Column2'] + 1;
}
My sorting code
foreach ($arr as $mks){
echo $mks['Column1'] . ", " . $mks['Column2'] . "<br>";
}
How do I get this to re-save into my array properly?! I've tried googling this for most of the morning but has lead to frustration.
I think this is what you need:
foreach ($arr as $key => $mks){
if ($mks[$key] == $Var) {
$arr[$key] = $mks+1;
}
}
Now, $arr will contain the modified array, and you can use / modify it further as you need.
I don't see any "sorting code" but you can try to use references "&" instead of copy vars in your foreach(s) :
foreach($arr as & $mks){
...
}
Instead of copying your cells it will to give you a reference and every modifications done on it will be saved in the array.
Try changing your array like this instead
foreach ($arr as $key => $mks){
if ($mks['Column1']==$Var) {$arr[$key]['Column2'] = $mks['Column2'] + 1;
}

PHP : how to use foreach loop inside an echo statement?

i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.

Categories