Inject internal array values

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 blow up detail_id

to get 1,4

.

I know it is possible with foreach and adding array values, but want to know if this is done by implode or any other built-in function in PHP

+3


source to share


4 answers


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 this

+2


source


Something like the following using join()

:



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

      

+3


source


Please check this answer.

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

echo implode(",",$b); 

      

+2


source


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

?>

      

0


source







All Articles