Reputation: 1196
This is my basic array:
Array (
[1] => array
(
[name] => Name1
[midname] => MidN1
[lastname] => LastN1
[email] => [email protected]
)
[2] => array
(
[name] => Name2
[midname] => MidN2
[lastname] => LastN2
[email] => [email protected]
)
[3] => array
(
[name] => Name1
[midname] => MidN1
[lastname] => LastN1
[email] => [email protected]
)
)
As you can see I have names and emails to be the same in some cases, the idea is to display only an array as follow
[1] => array
(
[name] => Name1
[midname] => MidN1
[lastname] => LastN1
[email] => [email protected]
)
[3] => array
(
[name] => Name1
[midname] => MidN1
[lastname] => LastN1
[email] => [email protected]
)
as you can see the name is the same but the email is different, so that is the idea to get all of the information from emails that are different, now, the problem is that name, midname, lastname and email is stored in a single column as json array: So first I:
$q = "SELECT * FROM table";
$r=$con->query($q);
$res = mysqli_fetch_array($r);
$arrs = json_decode($res);
print_r($arrs);
and that is how I get the array's ... and they get display in html as:
Name1 MidN1 LastN1 [email protected]
Name2 MidN2 LastN2 [email protected]
Name1 MidN1 LastN1 [email protected]
the idea is to get only:
Name1 MidN1 LastN1 [email protected]
Name1 MidN1 LastN1 [email protected]
I try to use array_unique($array); but that return empty and array_unique($array, SORT_REGULAR); that will output the whole thing, the [1]=>array()... is the ID from the row...
Thank you for taking the time.
Upvotes: 0
Views: 68
Reputation: 328
Quick solution if you are not able to change your table definition or your query: 1) Making an array where First name, middlename and lastname are primary key ( Problem is two John junior Smith)
$arr= array (
'1' => array
(
'name' => 'Name1',
'midname' => 'MidN1',
'lastname' => 'LastN1',
'email' => '[email protected]'
),
'2' => array
(
'name' => 'Name2',
'midname' => 'MidN2',
'lastname' => 'LastN2',
'email' => '[email protected]'
),
'3' => array
(
'name' => 'Name1',
'midname' => 'MidN1',
'lastname' => 'LastN1',
'email' => '[email protected]'
)
);
$people = array();
foreach($arr as $v){
$people[$v['name'].' '.$v['name'].' '.$v['name']][] = $v['email'];
}
ksort($people); // if it is not ordered by mysql
echo '<table border="1">';
foreach( $people as $k => $val){
echo "<tr><td>$k</td><td>";
foreach($val as $email){
echo $email.'<br>';
}
echo '</td></tr>';
}
echo '</table>';
Another solution is by using usort where you define your sorting criteria.
Upvotes: 0
Reputation: 1732
I edited my answer. You can iterate your Json result like this:
$my_array = array();
foreach ($arrs as $key => $value) {
if (!in_array($value['email'], $my_array)){
$my_array[] = $value['email'];
}
}
However I wonder why storing a Json string in a DB field instead of using a field per property...
Upvotes: 0