0

I want to implode this array to make a string with all keys = 'Palabra'. How can this be done? (the output should be: 'juana es')

Array
(
    [0] => Array
        (
            [Palabra] => juana
        )

    [1] => Array
        (
            [Palabra] => es
            [0] => Array
                (
                    [Raiz] => ser
                    [Tipo] => verbo
                    [Tipo2] => verbo1
                 )
        )
)
2
  • 1
    Did you try anything on your own? Commented Dec 19, 2011 at 6:55
  • I have workaround with a foreach but I want to know if there is a simpler method Commented Dec 19, 2011 at 6:58

3 Answers 3

1
function foo( $needly, $array ) {
    $results = array();
    foreach ( $array as $key => $value ) {
        if ( is_array( $value ) ) {
            $results = array_merge($results, foo( $needly, $value ));
        } else if ( $key == $needly ) {
            $results[] = $value;
        }
    }
    return $results;
}
echo implode( " ", foo( "Palabra", $your_array ) );
Sign up to request clarification or add additional context in comments.

Comments

1

I ended using the foreach for lack of a better solution:

foreach ($array as $key => $palabra) {
    $newArray[] = $array[$key]["Palabra"];
}

$string = implode(' ', $newArray);

Comments

-1

I think the simplest solution is with array_walk_recursive.

<?php
$arr = array(
    array(
        'Palabra' => 'juana',
    ),
    array(
        'Palabra' => 'es',
        array(
            'Raiz' => 'ser',
            'Tipo' => 'verbo',
            'Tipo2' => 'verbo1',
        ),
    ),
);

$str = array();

array_walk_recursive($arr, function($value, $key)  use(&$str) {
    if ($key == 'Palabra') {
        $str[] = $value;
    }
});

$str = implode(' ', $str);
echo "$str\n";

The function passed in is called for each key-value pair in the array and any subarrays. Here we append any values with a matching key to an array and then implode the array to get a string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.