3

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

4 Answers 4

3

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

echo join(',', array_map(function ($i) { return $i['Detail']['detail_id']; }, $array));
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

If we use long array, whether this will slow down the process.
@Jusnit: For long array array_reduce() will be a lot faster and memory efficient than rajmohan's solution. This is because, unlike array_map(), it does not need an intermediary array to do the job.
2

Please check this answer.

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

echo implode(",",$b); 

2 Comments

Oops, I upvoted your answer by mistake. This answer is incorrect.
Thanks @Tadeck. Please check this answer.
0
<?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);

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.