hellomello
hellomello

Reputation: 8597

PHP: checking array to see if values match, display those values

I am generating an array from a while loop, and I would like to eventually use this array to display data.

while($row = $database->fetch(PDO::FETCH_ASSOC)
{

     $value_1 = $row['value_1'];
     $value_2 = $row['value_2'];

     $data[] = array("value_1"=>$value_1,"value_2"=>$value_2);

}

so the $data[] would display using print_r I get something like this:

Array
(
    [0] => Array
        (
            [value_1] => Hello World
            [value_2] => venus
        )

    [1] => Array
        (
            [value_1] => Hello World
            [value_2] => pluto
        )

    [2] => Array
        (
            [value_1] => Hello Moon
            [value_2] => Halloween
        )

)

My question is, how would I do a foreach loop or display such a way where if I wanted to get all data, but consolidate the same values?

Ex:

Hello World to venus pluto
Hello Moon to Halloween

I know those sentences doesn't make sense, but as you can see Hello World would be consolidated and I would need to add an " to" in between value_1 and value_2

Hope my question is understandable.

Thanks!

Upvotes: 0

Views: 1259

Answers (3)

Kalpesh Patel
Kalpesh Patel

Reputation: 2822

I think for this first you need to create new array as follows:

$new_array = array();
//consider your original array is $data
foreach($data as $row){
    if (array_key_exists($row['value_1'], $new_array)) {
       $new_array[$row['value_1']] = $new_array[$row['value_1']]. " ". 
                                     $row['value_2'];
    }
    else {
        $new_array[$row['value_1']] = $row['value_2'];
    }
}

Then display it by iterating:

foreach($new_array as $key => $value){
   echo $key ."to". $value;
}

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

foreach($data as $d) {

    echo $d['value_1'], ' to ', $d['value_2']; // this is if you want to echo the content

    // this code is to insert 'to' in the middle of value_1 and value_2
    $value_2 = $d['value_2'];

    unset($d['value_2']);

    array_push($d, "to", $value_2);

    unset($value_2);

}

Also you don't need to assign the $row value to another value:

$value_1 = $row['value_1']; // remove this
$value_2 = $row['value_2']; // remove this

$data[] = array("value_1" => $row['value_1'], "value_2" => $row['value_2']);

Upvotes: -1

Justin John
Justin John

Reputation: 9615

Try something like this. (Not Tested)

$match = array();
foreach($data as $d) {
    if (isset($match[$d['value_1']])) {
        $match[$d['value_1']] = $match[$d['value_1']].' '.$d['value_2'] ;
    } else {
        $match[$d['value_1']] = $d['value_1']. ' to '. $d['value_2'];
    }
}

print_r($match);

Upvotes: 2

Related Questions