Looping through an array

I’ve got this array:

if( is_array( $detail ) ) { foreach( $detail as $key=>$value ) { 
$data = array(
    'Email' => $email,
    'EmailType' => 'Html',
    'dataFields' => array(
	array(
	'Key' => 'WISHLIST_CONTENTS',
	'Value' => nl2br( $value['detail'] ) ),
    array(
    'Key' => 'LIST_ID',
	'Value' => $list),
	)
	);
    } }

but nl2br( $value[‘detail’] ) never loops through the array, it just gives one result.

  1. nl2br() does not loop through anything. it’s a string function, after all.
  2. inside your loop you overwrite $data in each cycle.

I did try setting the value for the ‘WISHLIST_CONTENTS’ part of the array to this:

'Value' => if( is_array( $detail ) ) { foreach( $detail as $key=>$value ) { nl2br( $value['detail'] ) }} ),

but that just gave a lot of syntax errors. I know that nl2br just gives a line break but I want that to be part of it so that it’s like a list (or if not separated by a comma)

your use of foreach makes no sense here since you try to get a single value out of an array. maybe you can elaborate on the purpose of the $detail array in your code.

// alas, something that makes it valid (as of PHP 5.4)
// in case it is an array
$value = nl2br(end($detail)['detail']);
// otherwise …
// … do whatever should be done it that case

I’m not trying to get a single value but instead the details of every product the user has put in their wishlist. I’d ideally like each product to be separated by a comma and space to make it more legible.

$detail is the quantity of a product, the option (color, size etc) as well as the product name. Is that possible?

that’s easy.

$details = implode(', ', array_map(function ($item) {
    return nl2br($item['detail']);
}, $detail));

Thank you, is it possible to get two values in the same part? For example, detail and price before each comma?

sure.

Thanks, I did this in the end and it works great:

    if( is_array( $detail ) ) { foreach( $detail as $key=>$value ) { 
$details = implode(', ', array_map(function ($item) {
    return ($item['desc']." (".$item['detail'].")");
}, $detail));
    } }
	
$product_detail = strval($details);
$product_detail = str_replace('<br /> ', '', $product_detail);

....

    'EmailType' => 'Html',
    'dataFields' => array(
	array(
	'Key' => 'WISHLIST_CONTENTS',
	'Value' => $product_detail),

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.