Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have looked around and I see a lot of people asking how to implode arrays with nested arrays. However, these people usually want to include the nested array as well. I do not want to include the nested array... I want to throw out the nested array...

This is my array:

[tag] => Array
(
    [0] => one
    [1] => two
    [0_attr] => Array
        (
            [category] => three
            [lock] => four
        )

    [2] => five
)

If I implode this array, comma delimited, I want the result to be:

one, two, five

Notice how three and four are NOT included. Since they are a nested array, I don't want it. I only want immediate values. How exactly would I get this done?

share|improve this question
2  
You might want to add a tag for the language. –  TeaDrivenDev Nov 17 '10 at 10:48
    
are you just looking for an algorithm, or do you want code? If you want code, you'll need to let us know the language. –  Matt Ellen Nov 17 '10 at 10:58
add comment

1 Answer

up vote 1 down vote accepted

You would need to iterate all the values in $tag and filter out those is array
such as

$tags = array();
foreach ($tag as $index=>$value)
{
  if (!is_array($value))
  {
     $tags[$index] = $value;
  }
}
implode(',', $tags);

I found the above is a bit tedious,
here is the improved version

$arr = array(0 => "one", 1 => "two", 2 => array(1,2,3), 3=>4, 4=>new stdClass);
echo implode(",", array_filter($arr, "is_scalar"));

output :

one,two,4
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.