lisovaccaro
lisovaccaro

Reputation: 33956

Implode array joining only similar key?

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
                 )
        )
)

Upvotes: 0

Views: 91

Answers (3)

lisovaccaro
lisovaccaro

Reputation: 33956

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

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

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

Upvotes: 1

Eugene Manuilov
Eugene Manuilov

Reputation: 4361

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 ) );

Upvotes: 1

Michael Mior
Michael Mior

Reputation: 28762

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.

Upvotes: -1

Related Questions