Justin John
Justin John

Reputation: 9616

Implode an inner array values

An array

Array
(
    [0] => Array
    (
        [Detail] => Array
        (
            [detail_id] => 1
        )

    )

    [1] => Array
    (
        [Detail] => Array
        (
            [detail_id] => 4
        )

    )

)

Is it possible to use implode function with above array, because I want to implode detail_id to get 1,4.

I know it is possible by foreach and appending the array values, but want to know whether this is done by implode function or any other inbuilt function in PHP

Upvotes: 3

Views: 1151

Answers (4)

zerkms
zerkms

Reputation: 254926

If you need to use some logic - then array_reduce is what you need

$result = array_reduce($arr, function($a, $b) {
    $result = $b['Detail']['detail_id'];

    if (!is_null($a)) {
        $result = $a . ',' . $result;
    }

    return $result;
});

PS: for php <= 5.3 you need to create a separate callback function for that

Upvotes: 2

deceze
deceze

Reputation: 522125

What about something like the following, using join():

echo join(',', array_map(function ($i) { return $i['Detail']['detail_id']; }, $array));

Upvotes: 3

rajmohan
rajmohan

Reputation: 1618

Please check this answer.

$b = array_map(function($item) { return $item['Detail']['detail_id']; }, $test);

echo implode(",",$b); 

Upvotes: 2

user798596
user798596

Reputation:

<?php

$array = array(
    array('Detail' => array('detail_id' => 1)),
    array('Detail' => array('detail_id' => 4)),);

$newarray = array();

foreach($array as $items) {
    foreach($items as $details) {
        $newarray[] = $details['detail_id'];
    }
}

echo implode(', ', $newarray);

?>

Upvotes: 0

Related Questions