script888
script888

Reputation: 93

Combining each values of array to single array in php

I want combining each values from two arrays to single array, and have a code like this,

        $k = 'a,b';
        $db = '01,02,03,04,05';

        $dbe = explode(",", $db);
        $lenght = count($dbe);

        $kdata = explode(",", $k);
        $dbdata = explode(",", $db);

        if(sizeof($kdata) > sizeof($dbdata)){
                 $length = count($kdata);
            }else{
                  $length = count($dbdata);
        }       

    for($i=0; $i<$length; $i++)
    {

        foreach( $kdata as $p => $kop)
           {
             echo $kop.$dbdata[$p]. ",";
            }
    }

and get result ;

a01,b02,a01,b02,a01,b02,a01,b02,a01,b02,

but the result not i expected, the result i want like this :

a01, a02, a03, a04, a05, b01, b02, b03, b04, b05,

how do i resolve this code to get result that i want.

Upvotes: 1

Views: 42

Answers (2)

Sergey B.
Sergey B.

Reputation: 83

We do an array, then we want something with it and do it.

<?php
        $k = 'a,b';
        $db = '01,02,03,04,05';


        $kdata = explode(",", $k);
        $dbdata = explode(",", $db);


        foreach($kdata as $val){
            foreach($dbdata as $value){
                $items[] = $val.$value;
            }
        }

        $result = implode(", ", $items);
        echo $result;

?>

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57141

After your explode() to build the arrays you can do a nested foreach() to output the result your after...

$k = 'a,b';
$db = '01,02,03,04,05';

$kdata = explode(",", $k);
$dbdata = explode(",", $db);

foreach ( $kdata as $prefix) {
    foreach( $dbdata as $kop)
    {
        echo $prefix.$kop. ", ";
    }
}

Upvotes: 1

Related Questions