I am getting the values from an array this is taken from jQuery.serialize() just an input field. I then send then form data to a sendMail page.
Display the results in an email and the word Array is the first word then the value inputted follows, the rest of the data displayed is ok.
I have four arrays and in front of each the word Array appears.
$qty = $_POST['qty'];
foreach($qty as $value)
{
$qty .= $value . "<br>";
}
$desc = $_POST['description'];
foreach($desc as $value)
{
$desc .= $value . "<br>";
}
$options = $_POST['options'];
foreach($options as $value)
{
$options .= $value . "<br>";
}
$price = $_POST['price'];
foreach($price as $value)
{
$price .= $value . "<br>";
}
input would be qty: 1, Desc: description, options: small, price: 1.99
output is Array 1, Array description, Array options, Array small.
only on the first line the rest of the lines are ok.
You are concatenating to the POST array you should do this instead:
$qty = $_POST['qty'];
foreach($qty as $value)
{
$qty2 .= $value . "<br>";
}
echo $qty2;
Each part of your code contain the inconsistency of both assuming you have an array as POST-data and then assigning it as an string.
$possible_array = $_POST['possible_array'];
foreach($possible_array as $value)
{
$possible_array .= $value . "<br>"; // < - here you use $possible_array as a string
}
One way forward should be to assign the string value to another string:
$possible_array = $_POST['possible_array'];
foreach($possible_array as $value)
{
$string .= $value . "<br>"; // < - change to a new string
}
However it seem not probable that you actually have POST-data in arrays here I guess you send different items which each have the properties qty, description etc
I think you would like to use a solution where you iterate (foreach) on product info as an two-dimensional array, like $_POST['products']['qty'] where products is an array. But to help you further you would need to include your POST-data to see how its structured/serialized.
That happens because you append the value of each array to the array itself. Due to the value being a string the result also becomes a string. So the array will implicitly be casted to a string which results in the word "Array".
Possible solution:
$qtyList = implode('<br>' , $_POST['qty']);
Related
<?php
$names =array('Alex','Billy','Tabby');
$names_str=null;
foreach($names as $key => $names)
{
$names_str .= $name;
if(key!= (count($names)-1))
{
$names_str.=', ';
}
}
echo $names_str;
?>
why do we set names_str=null?
why do we put count($names-1)) how does this loop work?
<?php
$names = array('Alex','Billy','Tabby');
$names_str = null;
foreach($names as $key => $names)
{
$names_str .= $name;
if(key != (count($names) - 1))
{
$names_str .=', ';
}
}
echo $names_str;
?>
Why do we set $names_str = null?
It is being initialized outside of the loop. If this is a string to be returned, technically doing $names_str = ""; would work better if you want a default value to show and aren't doing some sort of empty/null check...
Why do we put count($names-1))?
This checks the key # e.g. (0,1,2) against the count/length of the array minus 1 (array starts at 0), to see if we are referencing the last key/value pair in the array, to determine if the string should show a comma between the current value and next value, or not. If it's the last value, we don't want to show a "," at the end of the string.
How does this loop work?
$names_str .= $name; concatenates the $name values to the initial string, with the if/key check placing commas between each value. See above about the count. So you end up with "Alex, Billy, Tabby" as the final value for $names_str.
A better way to do this is to use PHP's implode function:
$comma_separated = implode(",", $names);
This would give you the same comma separated list.
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 have been trying to create a Multidimensional array from an already existing array. The reason I am doing this is so I can separate the super array into a more categorized version so that later on I can run foreach on just those categories in another script.
This is a snippet of code // Please read comments :)
$and = array();
if($this-> input-> post('and')) // This is the super array and[] from a previous input field
{
if(preg_grep("/reason_/", $this-> input-> post('and'))) // Search for the reason_
{
foreach($this-> input-> post('and') as $value) // if reason_ is present
{
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
if(preg_grep("/status_/", $this-> input-> post('and'))) // Search for status
{
foreach($this-> input-> post('and') as $value) // If it is in the super array
{
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
This approach is not giving me expected outcome however, I am getting a big string like so :
array(2) { ["reason_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
["status_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
So to my knowledge (which is limited) when I try to do a foreach over the array
[reason_and]
I only get one loop since the array ["reason_and] only has one value (the 24 character string?). Is it possible to have the reason_and have a value for each of the numbers?
Is this even possible? I'm quite confused.
I've referred to this question for reference but I still do not get a outcome that I can work with. Thanks in advance.
This
$and['reason_and'] .= end(explode('_', $value)) . ' , ';
^^^^----
should be
$and['reason_and'][] = end(explode('_', $value)) . ' , ';
^^--
which turns it into an "array push" operation, not a string concatenation. Then 'reason_and' will be an array, and you foreach over it.
first of all preg_grep returns an array with matched values, so
$andArray = $this-> input-> post('and'); // This is the super array and[] from a previous input field
if($andArray) {
$reason = preg_grep("/reason_/", $andArray); // Search for the reason_
if($reason) { // if reason_ is present
foreach($reason as $value) {
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
$status = preg_grep("/status_/", $andArray); // Search for status
if($status) {
foreach($status as $value){ // If it is in the super array
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
Or if you need result as array, then remove ' , ' and replace dot with [];
I am attempting to generate a weekly email to users of my site that lists locations that have added new information. When someone adds information, a table receives two numbers, one for the state and the second for the county. The first step of my cron job is to take the numbers and convert them to county, state format (Alameda, California for example). At the end of each conversion I added a | to be used as a delimiter. This part works perfectly. Next I loop through each user to send this information via email but this part does not work. What I end up with is the word array instead of my county, state format. What am I missing?
This is the code that performs the 1st step, which works just fine:
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
$statename = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
$countyname = $county['Name'];
}
$locations = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "$countyname, $statename ". '</a>' . "|";
$i = $i + 1;
}
This is the code that I am using to explode the array into the county, state format, which does not function properly. Instead I get the word array.
$locals = explode("|", $locations);
$locals is used in the email message as the list of new information. Please point me in the right direction. Thanks
explode will give you array
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
so when you use explode function, it will explode string in to array
in your case .. write
$locals = explode("|", $locations);
echo "<pre>";print_r($locals);echo "</pre>";
and you will have exact idea and it will solve your problem
First, what is the purpose of $i?
Second, I think you want to concatenate $locations:
// This overwrites the variable - this is what you are doing
// at the end $locations will be the one single last link
$locations = '<a href="ht
// This adds to / concatenates - giving you a long strong of many links
$locations .= '<a href="ht
// ^ Note the period.
Third, explode does take a string and turns it into an array.
If you're making a long string, why would you want to explode it back into the parts you constructed it from?
I would suggest storing your states, countys, and constructed links in arrays. Then you can use the contents of those arrays at will to create your emails.
To look at what's in an array use print_r() or var_dump(). You can loop over arrays with foreach().
<?php
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
// There had better only be ONE statename per SID or you lose info!
$user_array[$i]['statename'] = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
// There had better only be ONE countyname per CID or you lose info!
$user_array[$i]['countyname'] = $county['Name'];
}
$user_array[$i]['link'] = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "{$user_array[$i]['countyname']}, {$user_array[$i]['statename']} ". '</a>';
++$i; // add one to i
}
// Show the arrays:
echo "<pre>";
print_r($user_array);
echo "</pre>";
?>
The above gives you an array like
Array
(
[0] => Array
(
[statename] => CA
[countyname] => San Bernardino
[link] => <a href="blah...
)
[1] => Array
(
[statename] => OR
[countyname] => Multnomah
[link] => <a href="yada...
)
)
To use the array just do
foreach ($user_array as $single_user_item) {
echo $single_user_item['link'];
}
I have XML file where I have name of currency and rate. I want to save those currencies and rate as pairs into an array, but it doesnt work, when I echo the array with foreach only last one appears.
Here's my code:
<?php
$xml = simplexml_load_file("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
$array=array();
foreach ($xml->children() as $cubeMain) {
foreach ($cubeMain->children() as $cubeTime) {
echo "Kursid seisuga: " . $cubeTime['time'];
foreach ($cubeTime->children() as $cubeCurr) {
$currency=$cubeCurr['currency'];
$rate=$cubeCurr['rate'];
$array = array((string)$currency => $rate);
echo $currency . " " . $rate . "<br />";
}
}
}
foreach ($array as $currency => $rate){
echo "$currency: $rate\n";
}
?>
try
$array[(string)$currency] = $rate;
instead of
$array = array((string)$currency => $rate);
If you expect to have several currency + rate couples, you'll want an array that contains sub-items, each one being made of currency + rate.
Typically, you'll first initialize your array :
$array = array();
Then, for each currency, you'll add an item into that array :
$array[] = array((string)$currency => $rate);
With that, you'll have a long list, but not indexed by currency -- which might not be that useful.
You'll probably, instead, prefer going with this second solution :
$array[(string)$currency] = $rate;
With that, your array will have the currency as key -- which make it much easier to find your data back, later.
Going with the second solution, your array is indexed by currency.
Which means you can find the rate for a specific currency this way :
echo $array['EUR']; // if EUR is an exinsting currency
And loop over all data like this :
foreach ($array as $currency => $rate) {
echo "$currency : $rate <br />";
}