Page 1 of 1

create string from multidim array

Posted: Tue Jan 15, 2008 12:27 am
by lafflin
Hello, I am trying to create a string with several variables taken from a multidimensional array. I have my array built and I have tested it, then stuck it into a session to pass it to another script. The script recieving the $_SESSION needs to iterate through both dimensions of it.
the array is 2 dimensions, the first (left) dimension is a line item and contains an array of the individual characteristics of that line.(item, price, qty, total).

so for instance, my array, was this:

Code: Select all

 
$sale_info[] = array("$item","$price","$qty","$combined") ;
 


and it is contained in a loop, each item placed in the shopping cart creates another array item.

I then

Code: Select all

 
$_SESSION['sale_info'] = $sale_info ;
 
and now I want to do something like this:

Code: Select all

 
foreach ($_SESSION['sale_info'] as $items)
 { "$items[0] \t $items[1] \t $items[2] \t $items[3] <br>"; }
 
and I want it to look like this
shirt 12.00 2 24.00
pants 21.00 2 22.00

This last bit is where I am stuck, I want to be able to return a string full of my values seperated by tabs and one break per line as one variable


any help is appreciated!

Re: create string from multidim array

Posted: Tue Jan 15, 2008 12:50 am
by jimthunderbird
PHP Code:

Code: Select all

 
$newline = "A newline is \n";
$return = "A carriage return is \r";
$tab = "A tab is \t";
$dollar = "A dollar sign is \$";
$doublequote = "A double-quote is \"";
 
Note: If you try to escape a character that doesn't need to be, such as an apostrophe, then the backslash will show up when you output the string.

These escaped characters are not very useful for outputting to a web page because HTML ignore extra white space. A tab, newline, and carriage return are all examples of extra (ignorable) white space. However, when writing to a file that may be read by human eyes these escaped characters are a valuable tool!
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

You are right using \t, for new line you should use \n instead of <br>

If you want the output looks like what you want in html, I suggest use <table>, <tr>,<td> stuffs

Re: create string from multidim array

Posted: Tue Jan 15, 2008 1:52 am
by lafflin
thanks, but the formatting isn't my issue, I'm more concerned with the logic of how to loop through my array and return all the values as a string in on variable.

Re: create string from multidim array

Posted: Tue Jan 15, 2008 3:24 am
by Kieran Huggins
check out array_map() and implode().