sujithayur
sujithayur

Reputation: 386

How to make a logical implementation of the below php code?

I need an out put like this.Can you please help me to sort this out?

a-1,2,4 
b-3

for the following code:

<?php
    $paytype = array('a','a','b','a');
    $payno= array(1,2,3,4);

    for($i=0;$i<count($paynum);$i++){
        $paytypes = $paytype[$i];
        $paynum = $payno[$i];

    }
?>

Please Help

Upvotes: 0

Views: 49

Answers (4)

dev87
dev87

Reputation: 164

just use this code.

$paytype = array('a','a','b','a');
    $payno= array(1,2,3,4);

    $result = array();
    for($i=0;$i<count($paytype);$i++){
        $result[$paytype[$i]][] = $payno[$i];
    }

    $var = '';
    foreach($result as $k => $v)
    {
        $var .= "{$k} - ". implode(",", $v) . "<br />";
    }


    print_r($var);

Result :

a - 1,2,4
b - 3

Upvotes: 0

Ravi Hirani
Ravi Hirani

Reputation: 6539

Another alternative:-

Just use a simple foreach loop:-

$paytype = ['a','a','b','a'];
$payno= [1,2,3,4];
$res = [];

foreach($paytype as $k=>$v){
  $res[$v] = empty($res[$v]) ? $payno[$k] : $res[$v].','.$payno[$k];
}

print '<pre>';print_r($res);

output:-

Array
(
    [a] => 1,2,4
    [b] => 3
)

If you want output

a-1,2,4 
b-3

then add one additional foreach at the end.

foreach($res as $k=>$v){
  echo "$k-$v<br>";
}

Upvotes: 0

Thamilhan
Thamilhan

Reputation: 13303

Just use array_unique, array_map and array_keys like this:

<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);

$uniqArr = array_unique($paytype);  //Get all the unique value from array

foreach ($uniqArr as $value) {
    echo $value . "-" . implode(",",array_map("matchVal",array_keys($paytype,$value)))."<br/>"; 
}

function matchVal($x) {
    global $payno;
    return $payno[$x];
}

Output:

a-1,2,4
b-3

Demo

Upvotes: 2

Dhara Parmar
Dhara Parmar

Reputation: 8101

You can try this:

<?php
    $paytype = array('a','a','b','a');
    $payno= array(1,2,3,4);
    $newArr = array();
    for($i=0;$i<count($paytype);$i++){
        if(!isset($newArr[$paytype[$i]])) {
            $newArr[$paytype[$i]] = $payno[$i];
        } else {
            $newArr[$paytype[$i]] = $newArr[$paytype[$i]].",".$payno[$i];
        }
    }
    print '<pre>';print_r($newArr);
?>

Output:

Array
(
    [a] => 1,2,4
    [b] => 3
)

Upvotes: 1

Related Questions