php array - implode only the second level if is_array

I have an array ... $fields

This contains variables of which some are single strings and some are arrays

I need to implode these second level arrays values with a || divider whilst still leaving them inside the $fields array

i.e.

	$fields = array(
		'contentid' => $resource->get('id'),
		'parent' => $resource->get('parent'),
		'var1' => $resource->get('tv1'),
		'var2' => $resource->get('tv2'),//if this is an array it needs to be imploded with ||
		'var3' => $resource->get('tv3'), //if this is an array it needs to be imploded with ||
	);

Open in new window

freshwaterwestAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Cornelia YoderArtistCommented:
<?php

$fields = array(
      'contentid' => "x",
      'var2' => array("a", "b", "c"),
      'var3' => "d"
   );

if (is_array($fields[var2]))
   $fields[var2] = implode('||',$fields[var2]);
if (is_array($fields[var3]))
   $fields[var3] = implode('||',$fields[var3]);

print_r($fields);

exit();

Open in new window

0
freshwaterwestAuthor Commented:
Hi thanks for the reply - I was thinking there might be a quicker way - perhaps a function or a foreach to do them all without individually listing - the actual $fields has quite a lot of keys/values - I've only shown a couple of examples here.

I wonder if I could do something like below but don't really know how without listing as you've done above:

	foreach($fields as $key => $value){
		if( is_array($value) ){
			$value = implode('||',$value);
		}
	}

Open in new window


cheers
0
Cornelia YoderArtistCommented:
Yes, certainly, if you don't know exactly which fields might be arrays, then just as you said.   Any kind of loop through the array $fields which checks each entry for is_array and then implodes it will work.
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

freshwaterwestAuthor Commented:
I'm not sure how exactly to get it to work though, my attempt above didn't seem to work so I must have the logic / syntax wrong - I'm not too sure how to work with $key / $value without spelling out each individual
0
Ray PaseurCommented:
thinking there might be a quicker way
"Quicker" matters when you're running a deployed script, and anything that manipulates PHP in-memory variables is going to be about as quick as you can imagine.  "Tuning" these parts does not usually matter -- the only place you can make a performance difference is when you tune the I/O subsystem, and in web development that is usually the database.

I think the solution described by @YoderCM forms the right approach, but it needs to use the correct quotation marks around the array keys.  If you want a slightly more generalized definition, this might make sense.  It's hard to know without seeing the data and if you want to post that, we can work with a better test case.
http://iconoun.com/demo/temp_freshwaterwest.php

<?php // demo/temp_freshwaterwest.php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28509381.html

// SOME TEST DATA
$fields = array
( 'contentid' => "x"
, 'var2' => array("a", "b", "c")
, 'var3' => "d"
)
;

// THE DELIMITER STRING
$glue = '||';

// THE INDEXES OF THE DATA ELEMENTS THAT MIGHT NEED TO BE IMPLODED
$dats = array
( 'var2'
, 'var3'
)
;

// SHOW THE "BEFORE" CONDITION
var_dump($fields);

// ITERATE OVER THE DATA ELEMENTS
foreach ($dats as $key)
{
    if (is_array($fields[$key])) $fields[$key] = implode($glue, $fields[$key]);
}

// SHOW THE "AFTER" CONDITION
var_dump($fields);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
freshwaterwestAuthor Commented:
thanks Ray - works perfectly...
0
Cornelia YoderArtistCommented:
You can do this:

foreach ($fields as $key => $value)
{
    if (is_array($fields[$key]))
      $fields[$key] = implode("||", $fields[$key]);
}
0
Ray PaseurCommented:
Thanks for the points, and please feel free if you want to share some points with Yodercm.  I already have enough points to orbit Saturn.

Regarding this code snippet... It would make sense only if you wanted to implode all of the arrays.  If you wanted to be selective about it, you would need to tell PHP which arrays to choose or which arrays to exclude.

foreach ($fields as $key => $value)
{
    if (is_array($fields[$key]))
      $fields[$key] = implode("||", $fields[$key]);
} 

Open in new window

BUT... If you want to post a follow-on question about this design, I'll be glad to take a look at it.  Using a multi-dimensional array and implode() is an unusual code construct.  If we truly understand the problem you're trying to solve we may be able to suggest some easier ways to get a handle on the problem.
0
Ray PaseurCommented:
To anyone coming upon this answer in the future... Before you use this code:
http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28509381.html#a40297280

Please read this article to see what you need to change about that code!  String literal array indexes must be quoted.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12241-Quotation-Marks-in-PHP.html
0
Cornelia YoderArtistCommented:
@Ray:  I'm surprised you don't know this, Ray.  This code



<?php
$fields = array(
      'contentid' => "x",
      'var2' => "d"
   );
$x = $fields[contentid];
$y = $fields[var2];
echo "$x,$y";
exit();



produces this output.  No quotes needed.

x,d
0
Ray PaseurCommented:
No quotes needed.
Right, but only under two circumstances, both of which depart a long way from best practices.

1. You have suppressed PHP Notice messages.  Many programmers do not know about Notice messages.  If you suppress these, and PHP does by default, you will never be told if your script relies on an undefined variable.  Most professionals raise the error reporting levels to get these messages.

2. There is not a constant contentid or var2.

This is all explained in the article.  Search the article text for Missing Quotation Marks Cause Time-Bombs.
http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/A_12241-Quotation-Marks-in-PHP.html

Then go back and try your script with error_reporting(E_ALL) to see what happens.  
<?php
error_reporting(E_ALL);
$fields = array(
      'contentid' => "x",
      'var2' => "d"
   );
$x = $fields[contentid];
$y = $fields[var2];
echo "$x,$y";
exit();

Open in new window

After that, define a constant like this and rerun the script to see what happens.
<?php
define('contentid', 'ABC');
$fields = array(
      'contentid' => "x",
      'var2' => "d"
   );
$x = $fields[contentid];
$y = $fields[var2];
echo "$x,$y";
exit();

Open in new window

If you ever build something of any consequence in PHP you will likely work with other programmers and you will likely have a coding standards document that is your daily bible.  In all my years of working with PHP I have never seen a coding standard that allowed the use of unquoted string literals in array indexes.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.