Sasha Sasha - 4 months ago 18
PHP Question

PHP - check if the current ID is the same as previous in foreach loop

I have this

foreach
loop:

foreach($dataSet1 as $data) {
$result .= '<tr>';
$result .= '<td bgcolor="#EBEBEB" width="100" class="veranda"><a href="/lookup.php?userID='.$data['CUST_ID'].'">' . $data['CUST_ID'] . '</a></td>';
$result .= '<td bgcolor="#EBEBEB" width="100" class="veranda">' . $data['LAST_NAME'] . '</td>';
$result .= '<td bgcolor="#EBEBEB" width="100" class="veranda">' . $data['PHONE'] . '</td>';
$result .= '<td bgcolor="#EBEBEB" width="100" class="veranda">' . $data['ORD_COUNT'] . '</td>';
$result .= '<td bgcolor="#EBEBEB" width="100" class="veranda">' . date('m/d/Y' ,strtotime($data['DATE_LAST'])) . '</td>';
$result .= '</tr>';
}


EDIT

I need to separate the users with bottom border, based on $data['CUST_ID'];

Example:

$data['CUST_ID'] = 2;
$data['CUST_ID'] = 2;
$data['CUST_ID'] = 2;
bottom-border;
$data['CUST_ID'] = 25;
$data['CUST_ID'] = 25;
bottom-border;
$data['CUST_ID'] = 2131;
bottom-border;...

Answer

Just save the previous ID in a variable and check it, and update it, in each loop iteration:

$previousId = '';
foreach($dataSet1 as $data):
    if ($previousId !== '' && $previousId !== $data['CUST_ID']) {
        // put a border
    }
    $previousId = $data['CUST_ID'];
    $result .= '<tr>';
    $result .= '<td bgcolor="#EBEBEB" width="100" class="veranda"><a href="/lookup.php?userID='.$data['CUST_ID'].'">' . $data['CUST_ID'] . '</a></td>';
    $result .= '<td bgcolor="#EBEBEB" width="100" class="veranda">' . $data['LAST_NAME'] . '</td>';
    $result .= '<td bgcolor="#EBEBEB" width="100" class="veranda">' . $data['PHONE'] . '</td>';
    $result .= '<td bgcolor="#EBEBEB" width="100" class="veranda">' . $data['ORD_COUNT'] . '</td>';
    $result .= '<td bgcolor="#EBEBEB" width="100" class="veranda">' . date('m/d/Y' ,strtotime($data['DATE_LAST'])) . '</td>';
    $result .= '</tr>';
endforeach;
Comments