hafizy Baharudin hafizy Baharudin - 6 months ago 32
PHP Question

PHP Imploding Multidimensional Array

I need to implode an multi-dimensional array in a string using implode, i tried using the

array_map
shown here: stackoverflow.com but i failed.

Array:

Array (
[0] => Array (
[code] => IRBK1179
[qty] => 1
)
[1] => Array (
[code] => IRBK1178
[qty] => 1
)
[2] => Array (
[code] => IRBK1177
[qty] => 1
)
)


Desired Output:

IRBK1179:1|IRBK1178:1|IRBK1177:1

Answer

Use foreach and implode() inner array with : and then implode() new array with |. Try below code.

$arr = Array ( 
        0 => Array ( 'code' => 'IRBK1179','qty' => 1 ),
        1 => Array ( 'code' => 'IRBK1178','qty' => 1 ),
        2 => Array ( 'code' => 'IRBK1177','qty' => 1 ) );
$newArr = array();
foreach ($arr as $row)
{
    $newArr[]= implode(":", $row);
}

echo $finalString = implode("|", $newArr);

Output

IRBK1179:1|IRBK1178:1|IRBK1177:1

Working Online Demo: Click Here

Comments