I'm using PHP 5 with mySQL:
$line = mysql_fetch_array($result, MYSQL_ASSOC);
When I do this, I can see the results of the query printed:
foreach ($line as $data)
{
echo ($data . ", ");
}
But if I do this instead:
echo ($line[0] . " " . $line[1] . " " . $line[2]);
I don't see anything. Also I can't assign a value from $line:
$values[] = $line[0]; // fails - doesn't assign anything
Why? And what should I be doing instead?
You've nominated to retrieve records as associative entries only (MYSQL_ASSOC). This means your $line array will not contain numeric indices.
If you only want numeric arrays, use mysql_fetch_row().
Associative only, mysql_fetch_assoc()
You can also retrieve a mixed numeric and associative array using mysql_fetch_array($result, MYSQL_BOTH) however this will give you duplicate entries in your foreach loop.
You told MySQL that you want to fetch the row as an array, which means $line is not a 0-index array, it's an associative array, which means the keys of the array are the column names of the table(s) you selected from.
var_dump($line); // Will display the keys
try:
echo ($line["id"] . " " . $line["id"] . " " . $line["id"]);
so instead of using a index number like [0] you use the corresponding column-name
Related
I have a return string from a 3rd party plugin that looks like a var_dump from an array. I'm trying to parse into a valid associative array. Looking at various examples and doing some tests with the code that follows. The last segment demonstrates the problem I'm having. I'm trying to parse out the data into a string and then programmatically create an array after my data string has been finished. When I do a print_r on $vegetables2, I get:
Array([0] => “Gourd”=”40 kilojoules”,”Artichoke”=”105 kilojoules”,”Cassava”=”550 kilojoules”)
And the echo $vegetables2["Artichoke"] produces no value. Can someone please guide me at the correct syntax to create the array equivalent to the first two examples?
//this works:
echo "From creating the entire array with a static string:<br/>";
$vegetables = array("Gourd"=>"40 kilojoules", "Artichoke"=>"105 kilojoules", "Cassava"=>"550 kilojoules");
echo "Artichoke: " . $vegetables["Artichoke"] . "<br/>";
//this works too
$vegetables1['Gourd'] = "40 kilojoules";
$vegetables1['Artichoke'] = "105 kilojoules";
$vegetables1['Cassava'] = "550 kilojoules";
echo "From creating one element at a time:<br/>";
echo "Artichoke: " . $vegetables1["Artichoke"] . "<br/>";
//this doesn't work
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
echo $strData ."<br/>";
$vegetables2 = array($strData);
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
$dd=str_replace('"','',"$strData");
$ff=explode(',',$dd);
foreach ($ff as $c)
{
$xx=explode('=',$c);
$vegetables2["$xx[0]"]=$xx[1];
}
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
This string is your input:
"Array ( [Gourd] => 40 kilojoules [Artichoke] => 105 kilojoules [Casava] => 550 kilojoules )"
use strpos() to locate "("
use strpos() to locate ")"
use substr() to get what is between ( and )
use explode to divide the result wherever "[" appears
use array() to start a new array
use foreach to reformat each piece
use explode to divide each piece wherever "=>" appears
use trim to remove excess characters (left and right)
use $data[$key] = $value to create a new array to your liking
I have a while loop that loops through line of text
while ($line_of_text = fgetcsv($file_processing, 4096)) {
In this while loop I assign variables to different parts of the array
IF($i > 0)
{
echo "</br>";
$account_type_id = $line_of_text[0];
echo "Account Type ID: " . $account_type_id. "<br>";
$account_number = $line_of_text[1];
echo "account_number = " . $account_number . "<br>";
This while loop loops through many lines. I am trying to find a way to say that
IF $account_type_id == 99 then add $account_number to an array. Then outside of the while loop print out the whole array of $account_numbers where $account_type_id == 99.
I have tried using print_r but it will only display the last array...
To add the element to an array, you can use array_push.
First you need to create the array (before the while loop):
$my_array = array();
Then, in the while loop, do this:
if ($account_type_id == 99) {
array_push($my_array, $account_number);
}
Then to display the array, either use print_ror var_dump. To make the array easier to read, you can also do this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Rocket H had the answer in the comment he posted
inside of your loop
if($account_type_id == 99){
$account_numbers[] = $account_number;
}
After loop
print_r($account_numbers);
Hi I have this array called $allextensionsforque. See print_r below.
Array ( [0] => Local/101#from-queue/n,0 [data] => Local/101#from-queue/n,0 )
I'm trying a foreach like below but its not showing any data on the echo. Can anyone help?
$allextensionsforqueu = mysqli_query($conqueue,"SELECT data FROM queues_details WHERE id = '1' AND keyword ='member'");
$allextensionsforque = mysqli_fetch_array($allextensionsforqueu);
$foo = "";
foreach ($allextensionsforque as $extensionrow)
{
$extensionrowstriped = substr($extensionrow['data'],6,3);
$foo = "' " . $extensionrowstriped . " ' ,";
}
echo $foo;
You don't have an array in $extensionrow, since it's only an one dimensional array. So you just need to replace $extensionrowstriped = substr($extensionrow['data'],6,3); with $extensionrowstriped = substr($extensionrow,6,3);.
Check for errors using mysqli_error(). Here is a simple approach, but you may want to improve it for production use:
$allextensionsforqueu = mysqli_query($conqueue,"...") or die(mysqli_error($conqueue));
Next, append your data to $foo instead of overwritting it in each loop:
$foo .= "' " . $extensionrowstriped . " ' ,";
Finally, verify that $extensionrow contains the data that you expect. substr() will return false if a match is not found.
Some assistance would be greatly appreciated:
The 'foreach' section works perfectly and echo's the result set perfectly; as soon as I try the implode it fails? Thank you!
$ctr = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$RespondentsResultSetArray[$ctr] = array(
"Firstname" => $row['cnt_firstname'],
"Lastname" => $row['cnt_lastname']
);
$ctr = $ctr + 1;
}
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
}
sqlsrv_free_stmt($stmt);
echo implode(', ',array_values($RespondentsResultSetArray));
try this
implode(',',$RespondentsResultSetArray);
You are passing an array of arrays to implode function. Here is a little deviation of your code, that should get you to the same result:
$full_array = array();
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
array_push($full_array,$key["Firstname"]);
array_push($full_array,$key["Lastname"]);
}
echo implode(', ',$full_array);
Also, for the future, try to chose smaller names for your variables, and use lowercase for your variable names and array index.
The php implode function accepts an array of strings.
You are not passing it an array of strings.
To user1844933 that just answered, your suggestion would pass implode an array of arrays. That won't work for the same reason.
$RespondentsResultSetArray=array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
array_push($RespondentsResultSetArray,$row['cnt_firstname'].' '.$row['cnt_lastname']);
}
$saved_to_variable=implode(', '$RespondentsResultSetArray);
Will create an array of strings which you can then implode
Since you recently commented that you want to save it to a variable rather than echo it, I just changed the last line of the example code. I believe that will give you the properly spaced, and delimited string that you desire.
since$RespondentsResultSetArray is multidimensional array use foreach loop before echo
$string = "";
foreach($RespondentsResultSetArray as $values)
{
echo implode(array_values($values),",");
$string= $string.",".implode(array_values($values),",");
}
$string=ltrim($string,",");
echo $string;
Demo
I'm a newbie and I have a very basic question about PHP arrays
Code:
While(!feof($file_handle))
{
$SecondRow = fgets($file_handle); //gets row
$trimmed = trim($SecondRow); //removes extra bits
$replace = array("'");
$finalstring = str_replace($replace, "_", $trimmed); //Still a string w/o "'"'s
$CleanString = preg_split("/[\s]*[,][\s]*/", $finalstring); //creates the array
//print_r($CleanString);
echo "Row " . $CleanString[1]. "<br/>"; //??????
.....
}//end while
the opened file has the following:
0001,sparta
0005,PURCHASING
...
...
...
Question:
When I echo "Row " . $array[0], I get the first column as expected. But when I echo "Row " . $array[1], I get an the "Undefined offset: 1" error. When the string is read into the array (via preg_split) aren't both
array[0]->0001 and array[1]->sparta set?
thanks.
Looking at your entire code, you're essentially replicating a native function like fgetcsv() or one of it's equivalents.
Just pick one and be done :)
As far as determining how to use the array, as noted in the comments use print_r or var_dump() to guide you. Also read up on PHP Arrays
This is because fgets() get one row at time (one row per "loop").