PHP foreach loop - php

I need to transfer the values from a PHP array into a JavaScript array so that it can be used in my application, I have managed to get up to this:
var Descriptions = array(<?php
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
echo $ID . "[" . $description . "]" . ",";
}
?>);
and it works fine except for one thing: I dont know how to tell PHP to not put a comma after the last array value. The extra comma is causing a syntax error so it breaks my code.
Thanks in advance for any ideas,
RayQuang

The quick and dirty way:
for($i = 0, $c = count($tasks); $i < $c; $i++) {
$task = $tasks[$i];
...
echo $ID . "[" . $description . "]" . (($i != $c-1) ? "," : '');
}
There are obviously other ways of accomplishing this, one way would be to build up a string and then use the trim() function:
$tasks_str = '';
foreach(...) {
...
$tasks_str .= ...
}
echo trim($tasks_str, ',');
Or, (my favorite), you could build up an array and then use implode on it:
$tasks_array = array();
foreach(...) {
...
$tasks_array[] = ...
}
echo implode(',', $tasks_array);

don't try to build it manually, use json_encode

var Descriptions = <?=json_encode($tasks);?>;

var DescriptionsString = <?php
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
echo $ID . "[" . $description . "]" . ",";
}
?>;
var Descriptions = DescriptionsString.split(',');

try,
var Descriptions = array(<?php
$str = '';
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
$str .= $ID . "[" . $description . "]" . ",";
}
echo trim($str,',');
?>);

Not one to miss out on a trend:
$out = array();
foreach ($tasks as $task) {
$ID = $task['ID'];
$description = $task['description'];
$out[] = $ID . "[" . $description . "]";
}
echo implode(',', $out);
Using implode().

Related

Laravel: Combine values in array

can I ask for your help? I have values in the array and I want to combine them to become one value. I want a result that 'gendesc' 'dmdnost' 'stredesc' 'formdesc' 'rtedesc' will be in one column. Thanks.
foreach($data as $item){
$tmp = array();
$tmp_item = (array) $item;
$tmp['description'] = $tmp_item['gendesc'];
$tmp['m1'] = $tmp_item['dmdnost'];
$tmp['m2'] = $tmp_item['stredesc'];
$tmp['m3'] = $tmp_item['formdesc'];
$tmp['m4'] = $tmp_item['rtedesc'];
$final_data [] = $tmp;
}
print_r($final_data);
Can you try
foreach($data as $item){
$tmp_item = (array) $item;
$tmp = $tmp_item['gendesc']
. ' ' . $tmp_item['dmdnost']
. ' ' . $tmp_item['stredesc']
. ' ' . $tmp_item['formdesc']
. ' ' . $tmp_item['rtedesc'];
$final_data[] = array('description' => $tmp);
}
print_r($final_data);
You want this?
foreach($data as $item){
$tmp = array();
// ver.1
$tmp['description'] = $item['gendesc']
. $item['dmdnost']
. $item['stredesc']
. $item['formdesc']
. $item['rtedesc'];
// ver.2 also you can use one-line shortcut with implode instead of ver.1
$tmp['description'] = trim(implode(" , ", $item));
$final_data[] = $tmp;
}
print_r($final_data);
Try this,
$i =0;
foreach($data as $item)
{
$tmp = [];
$tmp[$i]['description'] = $item['gendesc'];
$tmp[$i]['m1'] = $item['dmdnost'];
$tmp[$i]['m2'] = $item['stredesc'];
$tmp[$i]['m3'] = $item['formdesc'];
$tmp[$i]['m4'] = $item['rtedesc'];
$i++;
}
print_r($tmp);

php array values not being pushed onto associative array

I wrote a javascript function which takes in a string and parses it as an associative array.
function getValues(string){
var array_values = new Array();
var pairs_array = string.split('\n');
if(pairs_array[0] == 'SUCCESS'){
window.success = true;
}
for(x=1; x< pairs_array.length; x++){
var parsedValue = '';
//console.log(pairs_array[x] + "<br>");
var pair = pairs_array[x].split('=');
//console.log(pair[1]);
var variable = pair[0];
if(pair[1]){
var value = pair[1];
for(i=0; i< value.length; i++){
var character = value.charAt(i);
if(character == '+'){
parsedValue = parsedValue + character.replace('+', ' ');
}else{
parsedValue = parsedValue + value.charAt(i);
}
}
array_values[variable] = decodeURIComponent(parsedValue);
}else{
array_values[variable] = '';
}
}
return array_values;
}
Then the function is called on the string window.name_value_pairs as follows
var array_callback = getValues(window.name_value_pairs);
for(x in array_callback){
console.log("call" + x + " " + array_callback[x]);
}
Works fine. Now i have been trying to write the function in php because i would prefer it on the server side but it is not working out. I'm not sure if the array values ar getting pushed onto the array because nothing gets returned. heres the php code i have tried:
Note: $results_values is a string
$result_values = $_REQUEST['result_values'];
echo "php array " . getValuesPhp($result_values);
function getValuesPhp($string){
$array_values = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true;
echo "TRUE";
}
for($x=1; $x< count($pairs_array); $x++){
$parsedValue = '';
$pair = explode("=",$pairs_array[$x]);
$variable = $pair[0];
if(isset($pair[1])){
$value = $pair[1];
for($i=0; $i< strlen($value); $i++){
$character = $value[$i];
//echo "char \n" . $character;
if(strpos($character, '+') !== false){
//echo "plus";
$parsedValue .= str_replace('+', ' ', $character);
}else{
//echo "hi2";
$parsedValue .= $value[$i];
}
}
echo "\n var " . $variable;
echo "\n parsed " . $parsedValue;
$array_values['" . $variable . "'] = $parsedValue;
//echo "arrayValues " . $array_values['" . $variable . "'];
//array_push($GLOBALS[$array_values]['" . $variable . "'], $parsedValue);
}else{
$array_values['" . $variable . "'] = '';
//array_push($GLOBALS[$array_values]['" . $variable . "'], '');
}
}
//echo "array payment stat" . $array_values['payment_status'];
return $array_values;
}
note: where it says $array_values['" . $variable . "'] this does print out the write result as it goes through the loop however it seems like the array elements are not being added to the array as nothing is returned at the end.
Thanks for any help
Sarah
Update:
#ChrisWillard I would like to return an associative array from the string. the string is in the format where each line is in the form key=value .. it is actually the string which comes back from a paypal pdt response. For example:
SUCCESS
mc_gross=3.00
protection_eligibility=Eligible
address_status=confirmed
item_number1=3
tax=0.00
item_number2=2
payer_id=VWCYB9FFJ
address_street=1+Main+Terrace
payment_date=14%3A26%3A14+May+22%2C+2014+PDT
payment_status=Completed
charset=windows-1252
address_zip=W12+4LQ
mc_shipping=0.00
mc_handling=0.00
first_name=Sam
address_country_code=GB
address_name=Sam+Monks
custom=
payer_status=verified
business=mon%40gmail.com
address_country=United+Kingdom
num_cart_items=2
mc_handling1=0.00
mc_handling2=0.00
address_city=Wolverhampton
payer_email=monks%40gmail.com
mc_shipping1=0.00
mc_shipping2=0.00
tax1=0.00
tax2=0.00
txn_id=3PX5572092U
payment_type=instant
last_name=Monks
address_state=West+Midlands
item_name1=Electro
receiver_email=mon%40gmail.com
item_name2=Dub
quantity1=1
quantity2=1
receiver_id=WHRPZLLP6
pending_reason=multi_currency
txn_type=cart
mc_gross_1=1.00
mc_currency=USD
mc_gross_2=2.00
residence_country=GB
transaction_subject=
payment_gross=3.00
thanks for all your answers and help. it was a combination of two things that caused it to not print.. firstly my silly syntax error (being just new at programming haha I wont go into the logic i had behind this but it did make sense to me at the time haha) $array_values['" . $variable . "'] = $parsedValue; changed to this:
$array_values[$variable] = $parsedValue;
it was also the line
echo "php array" . getValuesPhp($result_values); that caused it not to print.
when i changed this to
print_r(getValuesPhp($result_values)); it printed perfect thanks to #ChrisWillard for this. So here is my final code. A combination of #ChrisWillard answer and #Mark B and #Jdo answers. I also wanted to check first if pair[1] existed and go through each character of pair[1] changing any '+' to a space ' ' if it existed so that it could be read by the user. Now i have found the function to do this for me haha. I'm sure it is not new information for a lot of you but for anyone who doesn't know it is urldecode so you can see below ive commented out the loop that i did not need (going through the characters of the string changing the plus value) and instead ive written: $finished_array[$key] = urldecode($value); thanks for all your help.
$result_values = $_REQUEST['result_values'];
print_r(getValuesPhp($result_values));
function getValuesPhp($string){
$finished_array = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true;
//echo "TRUE";
}
for($x=1; $x< count($pairs_array); $x++){
$parsedValue = '';
$pair = explode("=",$pairs_array[$x]);
$key = $pair[0];
if(isset($pair[1])){
$value = $pair[1];
//for($i=0; $i< strlen($value); $i++){
//$character = $value[$i];
//if(strpos($character, '+') !== false){
//$parsedValue .= str_replace('+', ' ', $character);
//}else{
//$parsedValue .= $value[$i];
//}
//}
$finished_array[$key] = urldecode($value);
}else{
$finished_array[$key] = '';
}
}
return $finished_array;
}
This is totally non-sensical:
$array_values['" . $variable . "'] = $parsedValue;
You're literally using " . $variable . " as your array key - remember that '-quoted strings do NOT expand variables.
Why not just
$array_values[$variable] = $parsedValue
From what I can gather, this should get you what you need:
$result_values = $_REQUEST['result_values'];
print_r(getValuesPhp($result_values));
function getValuesPhp($string){
$finished_array = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true; ////Not sure what you're trying to do here
}
for($x=1; $x< count($pairs_array); $x++) {
$pair = explode("=",$pairs_array[$x]);
$key = $pair[0];
$value = $pair[1];
$finished_array[$key] = $value;
}
return $finished_array;
}

How to iterate this in a foreach construct

This one only covers the first record in the array -- $form[items][0][description]. How could I iterate this to be able to echo succeeding ones i.e
$form[items][1][description];
$form[items][2][description];
$form[items][3][description];
and so on and so forth?
$array = $form[items][0][description];
function get_line($array, $line) {
preg_match('/' . preg_quote($line) . ': ([^\n]+)/', $array['#value'], $match);
return $match[1];
}
$anchortext = get_line($array, 'Anchor Text');
$url = get_line($array, 'URL');
echo '' . $anchortext . '';
?>
This should do the trick
foreach ($form['items'] as $item) {
echo $item['description'] . "<br>";
}
I could help you more if I saw the body of your get_line function, but here's the gist of it
foreach ($form['items'] as $item) {
$anchor_text = get_line($item['description'], 'Anchor Text');
$url = get_line($item['description'], 'URL');
echo "{$anchor_text}";
}
You can use a for loop to iterate over this array.
for($i=0; $i< count($form['items']); $i++)
{
$anchortext = get_line($form['items'][$i]['description'], 'Anchor Text');
$url = get_line($form['items'][$i]['description'], 'URL');
echo '' . $anchortext . '';
}

How to implode foreach

How to implode foreach() with comma?
foreach($names as $name) {
//do something
echo '' . $name .'';
}
Want to add comma after each link, except the last one.
Raveren's solution is efficient and beautiful, but here is another solution too (which can be useful in similar scenarios):
$elements = array();
foreach($names as $name) {
//do something
$elements[] = '' . $name .'';
}
echo implode(',', $elements);
You need to transform your array instead of iterating using foreach. You can do this with array_map.
PHP 5.3 syntax with closures
echo implode(", ", array_map(function($name) use($url, $title)
{
return '' . $name .'';
}, $names));
Compatible syntaxe before PHP 5.3
function createLinkFromName($name)
{
return '' . $name .'';
}
echo implode(", ", array_map('createLinkFromName', $names));
PHP 5.3 syntax with a better reability
function a_map($array, $function)
{
return array_map($function, $array);
}
echo implode(", ", a_map($names, function($name) use($url, $title)
{
return '' . $name .'';
}));
$first = TRUE;
foreach($names as $name) {
//do something
if(!$first) { echo ', '; }
$first = FALSE;
echo '', $name, '';
}
$s = '';
foreach ($names as $name) {
if ($s) $s .= ', ';
$s .= '' . $name . '';
}
foreach($names as $name) {
//do something
$str .= '' . $name .',';
}
echo substr($str,0,-1);
EDIT:
as the comments point out, this way of doing things is a little error prone if you change the separator (precisely its length) and forget the substr parameter. So use the foreach method unless performance is absolutely critical.
Here is an ugly solution using echo:
$total = (count($names) - 1 );
foreach($names as $i => $name)
{
if($i != $total)
echo '' . $name .', ';
else
echo '' . $name .'';
}

PHP Dynamic Breadcrumb

I got this code from someone and it works very well, I just want to remove the link from the last element of the array:
//get rid of empty parts
$crumbs = array_filter($crumbs);
$result = array();
$path = '';
foreach($crumbs as $crumb){
$path .= '/' . $crumb;
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumb));
$result[] = "$name";
}
print implode(' > ', $result);
This will output for example:
Content > Common > File
I just want a to remove the link from the last item - "File" to be just plain text..
I tried myself to count the array items and then if the array item is the last one then to print as plain text the last item.. but I'm still noob, I haven't managed to get a proper result..
Thank you!
This should work:
$crumbs = array_filter($crumbs);
$result = array(); $path = '';
//might need to subtract one from the count...
$count = count($crumbs);
foreach($crumbs as $k=>$crumb){
$path .= '/' . $crumb;
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumb));
if($k != $count){
$result[] = "$name";
} else {
$result[] = $name;
}
}
print implode(' > ', $result);
You could simply tweak your existing code to use a 'normal' loop (rather than a foreach iterator) to achieve this.
For example:
//get rid of empty parts
$crumbs = array_filter($crumbs);
$result = array();
$path = '';
$crumbCount = count($crumbs);
for($crumbLoop=0; $crumbLoop<$crumbCount; $crumbLoop++) {
$path .= '/' . $crumbs[$crumbLoop];
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumbs[$crumbLoop]));
$result[] = ($crumbLoop != $crumbCount -1) ? "$name" : $name;
}
print implode(' > ', $result);
N.B: I don't have access to PHP at the moment, so the above might not be error free, but you should get the idea.
for($i=0;$i< sizeof($crumbs);$i++) {
$path .= '/' . $crumbs[$i];
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumbs[$i]));
if ($i != sizeof($crumbs)-1) {
$result[] = "$name";
}else {
$result[] = $name;
}
}

Categories