[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

php array - implode only the second level if is_array

Posted on 2014-09-01
13
Medium Priority
?
933 Views
Last Modified: 2014-09-06
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

0
Comment
Question by:freshwaterwest
  • 4
  • 4
  • 3
11 Comments
 
LVL 27

Assisted Solution

by:Cornelia Yoder
Cornelia Yoder earned 1000 total points
ID: 40297280
<?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
 

Author Comment

by:freshwaterwest
ID: 40297291
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
 
LVL 27

Expert Comment

by:Cornelia Yoder
ID: 40297311
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:freshwaterwest
ID: 40297347
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
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1000 total points
ID: 40297416
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
 

Author Comment

by:freshwaterwest
ID: 40297472
thanks Ray - works perfectly...
0
 
LVL 27

Expert Comment

by:Cornelia Yoder
ID: 40297475
You can do this:

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

Expert Comment

by:Ray Paseur
ID: 40297489
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40299657
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
 
LVL 27

Expert Comment

by:Cornelia Yoder
ID: 40299720
@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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40299829
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

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month18 days, 16 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question