Show only unique values from Array - php

I have the following array in php:
array(12) {
[0]=>
array(2) {
["adress"]=>
string(17) "Kungsvägen 118 A "
["dob"]=>
string(10) "1969-06-17"
}
[1]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1969-06-17"
}
[2]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1980-05-22"
}
[3]=>
array(2) {
["adress"]=>
string(12) "Myntvägen 8 "
["dob"]=>
string(10) "1980-05-22"
}
[4]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1993-05-09"
}
[5]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1989-06-28"
}
[6]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1991-03-17"
}
[7]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1989-10-30"
}
[8]=>
array(2) {
["adress"]=>
string(23) "Gasslanda VÄSTERGÅRD 2 "
["dob"]=>
string(10) "1980-10-30"
}
[9]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1980-10-30"
}
[10]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1990-05-01"
}
[11]=>
array(2) {
["adress"]=>
string(11) "Ågatan 6 A "
["dob"]=>
string(10) "1990-05-01"
}
}
I want to print out the unique adress-values in this array when I'm doing an foreach. As you can see, Skolgatan 1 B appears several times in the array, so I want to print it out just once in my loop. How can I do this? I have tried
array_unique([$newArray['adress']);
but that does not work.

$unique = array();
foreach($array as $item)
$unique[$item['adress']] = $item;
Then use $unique

Something like this should work:
$printed_vals = array();
foreach ($array as $item) {
if (!in_array($item['adress'], $printed_vals)) {
print_r($item);
$printed_vals[] = $item['adress'];
}
}

This is how I would have solved this problem. Hope it helps.
$non_duplicates = array();
$i=0;
foreach( $addresses AS $address ){
if( !in_array( $address['adress'], $non_duplicates ) ){
// Use one of the below array_push statements
array_push( $non_duplicates, $i ); // if you want to get the array key position
array_push( $non_duplicates, $address['adress'] ); // if you only want a new array of unique addresses
}
$i++;
}
If you have chosen to only return key positions to $non_duplicates yo can then retrieve your unique positions from you array by:
foreach( $non_duplicates AS $key ){
echo $addresses[$key];
}

I guess you want to print address once but dob in multiple times.. in that case you can do something like followings
$printed_vals = array();
foreach ($array as $item) {
$printed_vals[$item['adress']][] = $item['dob'];
}
foreach ($printed_vals as $address => $values) {
echo $address . " => " . implode(",", $values);
}

Related

Search with PHP inside MongoDB

Im trying many days now to select data from this db
[1]: https://i.stack.imgur.com/QA34L.jpg
I want to print for example all comments
echo $comment['username']." | "; \ Alex | Alex
My php code so far:
[![$m= new MongoDB\Client ("mongodb://127.0.0.1/");
$db = $m->stores;
$collection = $db->storeinfo;][1]][1]
$storez = $collection->find(array("Products.pTHUMBNAIL" => $pThumb));
$o=1;
$afm=array();
foreach ($storez as $stor) {
$afm[$o] = $stor['AFM'];
$record = $collection->findOne(array(
"AFM" => $afm[$o],"Products.pTHUMBNAIL" => $pThumb));
foreach ($record['Products'] as $pro){
if($pThumb == $pro['pTHUMBNAIL']){
echo $temp = $pro['pID']." ";
foreach($pro as $pro1['pCOMMENTS']) {
foreach($pro1 as $com['Comment']) {
var_dump($com['Comment']);
/*
foreach($com as $comment) {
echo $comment['username'];
}
*/
}
}
}
}
$o += 1;
}
It seems that i just cannot find the correct foreach to loop through my Comment array
var_dump output:
099360111/1 object(MongoDB\BSON\ObjectId)#55 (1) { ["oid"]=> string(24) "6003403a695900000c002649" } string(11) "099360111/1" string(9) "Old Skool" string(2) "75" string(4) "Vans" string(25) "Leather and textile upper" string(2) "44" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "7" object(MongoDB\Model\BSONArray)#65 (1) { ["storage":"ArrayObject":private]=> array(1) { [0]=> object(MongoDB\Model\BSONDocument)#10 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#73 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#45 (1) { ["milliseconds"]=> string(13) "1611028053000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } } } 099360666/1 object(MongoDB\BSON\ObjectId)#44 (1) { ["oid"]=> string(24) "6006563a3f1c0000c80034a8" } string(11) "099360666/1" string(12) "old school 2" string(2) "50" string(4) "Vans" string(11) "black/white" string(8) "42,43,43" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "6" object(MongoDB\Model\BSONArray)#79 (1) { ["storage":"ArrayObject":private]=> array(2) { [0]=> object(MongoDB\Model\BSONDocument)#7 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#39 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#68 (1) { ["milliseconds"]=> string(13) "1611028089000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } [1]=> object(MongoDB\Model\BSONDocument)#78 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#77 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#76 (1) { ["milliseconds"]=> string(13) "1611030745000" } ["text"]=> string(8) "good!!!!" ["rating"]=> string(1) "5" } } } } } }
What about this?
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach ($comments['Comment'] as $comment) {
echo $comment['text'];
}
}
You used foreach() bad: the index should be added to the first parameter, not in the 'as' part.
Also it helps if you use more clear variable names. That doesn't take too much, but makes it more readable and easy to debug.
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach($comments as $comment) {
echo $comment['text'];
}
}

how to get the index of every array on multidimensional array with unknown depth in php

array(2) { [0]=> array(2) { ["name"]=> string(16) "Daerah Pertanian" ["sub"]=> array(6) { [0]=> array(2) { ["name"]=> string(5) "Sawah" ["value"]=> string(3) "145" } [1]=> array(2) { ["name"]=> string(18) "Sawah Pasang Surut" ["value"]=> string(3) "455" } [2]=> array(2) { ["name"]=> string(6) "Ladang" ["value"]=> string(3) "678" } [3]=> array(2) { ["name"]=> string(10) "Perkebunan" ["value"]=> string(3) "688" } [4]=> array(2) { ["name"]=> string(19) "Perkebunan Campuran" ["value"]=> string(3) "966" } [5]=> array(2) { ["name"]=> string(16) "Tanaman Campuran" ["value"]=> string(3) "565" } } } [1]=> array(2) { ["name"]=> string(22) "Daerah Bukan Pertanian" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(18) "Hutan Lahan Kering" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(25) "Hutan Lahan Kering Primer" ["value"]=> string(3) "566" } [1]=> array(2) { ["name"]=> string(27) "Hutan Lahan Kering Sekunder" ["value"]=> string(3) "255" } } } [1]=> array(2) { ["name"]=> string(17) "Hutan Lahan Basah" ["sub"]=> array(2) { [0]=> array(1) { ["name"]=> string(24) "Hutan Lahan Basah Primer" } [1]=> array(1) { ["name"]=> string(26) "Hutan Lahan Basah Sekunder" } } } } } }
I have an array like I mention above, so I want to print out every "name" key including the index (number) of it's array parent,
for example when I print out "Tanaman Campuran" so all index parent is (0)(5) and when I print "Hutan Lahan Basah Sekunder" the index parent is (1)(1)(1)
how can I achieve it?
here is some recursive function that I've tried
$GLOBALS['all'] = '';
function printout($arr){
foreach ($arr as $ia=>$a){
if(is_array($a)){
foreach ($a as $ib=>$b){
if(is_array($b)){
printout($b);
}
else{
if ($ib == 'name') {
$GLOBALS['all'] .= $ia;
echo '<tr>';
echo '<td>' . $b . ' (' . $ia . ')</td>';
echo '</tr>';
$GLOBALS['all'] = '';
}
}
}
}
}
}
*sorry for my bad explanation, I hope you guys can understand it
You could use the following function:
function search(array $array, $name)
{
foreach ($array as $key => $entry) {
if ($entry['name'] === $name) {
return [$key];
}
if (isset($entry['sub']) && $found_keys = search($entry['sub'], $name)) {
return array_merge([$key], $found_keys);
}
}
return null;
}
It returns:
if the value was directly found, an array of one containing the associated index,
if it wasn't but was found in any descendant item, an array merging its index with the indices of said descendant,
null if it wasn't found in that part of the tree.
Note: if a given name is present several times, it will only find the first occurrence.
Demo: https://3v4l.org/1hGr1

How to get max and min value in a multidimensional array

I have this array :
array(8) {
[0]=>
array(2) {
["ticket_type"]=>
string(9) "normal"
["ticket_price"]=>
string(5) "82.00"
}
[1]=>
array(2) {
["ticket_type"]=>
string(9) "cheaper"
["ticket_price"]=>
string(5) "62.00"
}
[2]=>
array(2) {
["ticket_type"]=>
string(9) "normal"
["ticket_price"]=>
string(6) "182.00"
}
[3]=>
array(2) {
["ticket_type"]=>
string(9) "cheaper"
["ticket_price"]=>
string(6) "162.00"
}
[4]=>
array(2) {
["ticket_type"]=>
string(9) "normal"
["ticket_price"]=>
string(6) "103.00"
}
[5]=>
array(2) {
["ticket_type"]=>
string(9) "cheaper"
["ticket_price"]=>
string(5) "63.00"
}
[6]=>
array(2) {
["ticket_type"]=>
string(9) "normal"
["ticket_price"]=>
string(6) "203.00"
}
[7]=>
array(2) {
["ticket_type"]=>
string(9) "cheaper"
["ticket_price"]=>
string(6) "163.00"
}
}
I want to get the min and max price for "normal" and "cheap" ticket category, there will be more ticket categories, so can't hard code it, will get from DB, how can I do that? I'm using PHP 5.6 now, need export as array or json, Let me know if need more details.
Thank you
You can do it at the SQL level:
SELECT MIN(ticket_price) AS min_ticket_price, MAX(ticket_price) as max_ticket_price, ticket_type
FROM {your_table_name}
WHERE {your_conditions}
GROUP BY ticket_type
If you still want to do it in PHP you can just loop the array and to sort the ticket types then get the min and max values.
foreach($arr as $ticket){
$new[$ticket["ticket_type"]][] = $ticket["ticket_price"];
}
// loop the new array to only get the max and min values of each ticket type
foreach($new as $key => $n){
$res[$key]["max"] = max($n);
$res[$key]["min"] = min($n);
}
output:
array(2) {
["normal"]=>
array(2) {
["max"]=>
string(6) "203.00"
["min"]=>
string(5) "82.00"
}
["cheaper"]=>
array(2) {
["max"]=>
string(6) "163.00"
["min"]=>
string(5) "62.00"
}
}
https://3v4l.org/RcCHZ
Here is a solution to do on the php level:
$prices = [
["ticket_type"=>"normal", "ticket_price"=>"82.00"],
["ticket_type"=>"cheaper", "ticket_price"=>"62.00"],
["ticket_type"=>"normal", "ticket_price"=>"182.00"],
["ticket_type"=>"cheaper", "ticket_price"=>"162.00"],
["ticket_type"=>"normal", "ticket_price"=>"103.00"],
["ticket_type"=>"cheaper", "ticket_price"=>"63.00"],
["ticket_type"=>"normal", "ticket_price"=>"203.00"],
["ticket_type"=>"cheaper", "ticket_price"=>"163.00"],
];
// STEP:1 group by ticket types
$grouped_array = [];
foreach($prices as $price) {
$ticket_type = $price["ticket_type"];
$grouped_array[$ticket_type][] = $price["ticket_price"];
}
/*
$grouped_array = [
"normal" => ["82.00", "182.00", "103.00", "203.00"],
"cheaper => ["62.00", "162.00", "63.00", "163.00"]
];
*/
function minMax($type_array) {
$min_max = ['min'=> min($type_array), 'max'=>max($type_array)];
return $min_max;
}
// STEP 2: find min and max in each category
$min_max = [];
foreach($grouped_array as $type => $prices) {
$min_max[$type] = minMax($prices);
}
/*
$min_max = [
"normal" => ["min"=>"82.00", "max"=>"203.00"],
"cheaper => ["min"=>"62.00", "max"=>"163.00"]
];
*/
However, doing it on the database layer is best in your case. this answers "How to get max and min value in a multidimensional array".

Print an array value only once - but still print rest of array? [duplicate]

This question already has answers here:
How can i list has same id data with while loop in PHP? [closed]
(1 answer)
php get unique sub array [duplicate]
(1 answer)
Closed 4 years ago.
been using most of the day to solve my problem - and i am about to give up.
I have an array looking like this:
array(2) {
[1]=>
array(5) {
[0]=>
array(6) {
["name"]=>
string(15) "Henning smaall"
["drivernumber"]=>
string(4) "8830"
["period_start"]=>
string(10) "2018-07-20"
["period_end"]=>
string(10) "2018-07-31"
["status"]=>
string(1) "0"
["note"]=>
string(9) "Operation"
}
[1]=>
array(6) {
["name"]=>
string(15) "Henning smaall"
["drivernumber"]=>
string(4) "8830"
["period_start"]=>
string(10) "2018-07-17"
["period_end"]=>
string(10) "2018-07-17"
["status"]=>
string(1) "0"
["note"]=>
string(0) ""
}
[2]=>
array(6) {
["name"]=>
string(15) "Henning smaall"
["drivernumber"]=>
string(4) "8830"
["period_start"]=>
string(10) "2018-07-16"
["period_end"]=>
string(10) "2018-07-16"
["status"]=>
string(1) "1"
["note"]=>
string(0) ""
}
[3]=>
array(6) {
["name"]=>
string(15) "Henning smaall"
["drivernumber"]=>
string(4) "8830"
["period_start"]=>
string(10) "2018-07-27"
["period_end"]=>
string(10) "2018-07-27"
["status"]=>
string(1) "0"
["note"]=>
string(0) ""
}
[4]=>
array(6) {
["name"]=>
string(15) "Henning smaall"
["drivernumber"]=>
string(4) "8830"
["period_start"]=>
string(10) "2018-07-31"
["period_end"]=>
string(10) "2018-07-31"
["status"]=>
string(1) "1"
["note"]=>
string(0) ""
}
}
[13]=>
array(2) {
[0]=>
array(6) {
["name"]=>
string(15) "Henrik Hjersing"
["drivernumber"]=>
string(4) "8850"
["period_start"]=>
string(10) "2018-07-10"
["period_end"]=>
string(10) "2018-07-24"
["status"]=>
string(1) "0"
["note"]=>
string(0) ""
}
[1]=>
array(6) {
["name"]=>
string(15) "Henrik Hjersing"
["drivernumber"]=>
string(4) "8850"
["period_start"]=>
string(10) "2018-07-18"
["period_end"]=>
string(10) "2018-08-01"
["status"]=>
string(1) "0"
["note"]=>
string(11) "asdasdasdad"
}
}
}
The output i am looking for should be something like
Henning smaall (8830)
2018-07-20 - 2018-07-31
2018-07-17 - 2018-07-17
2018-07-16 - 2018-07-16
2018-07-27 - 2018-07-27
2018-07-31 - 2018-07-31
Henrik Hjersing (8850)
2018-07-10 - 2018-07-24
2018-07-18 - 2018-08-01
For now i am using dummy data and easy php testcode - but i keep getting the name reccuring in the output.
Database function:
public function resultsetGroup(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
}
SQL function:
public function getVacations(){
//$this->db->query('SELECT * FROM vacation ORDER BY user_id, status, period_start');
$this->db->query('SELECT u.id, u.name, u.drivernumber, v.period_start, v.period_end, v.status, v.note FROM users u, vacation v where u.id = v.user_id');
$results = $this->db->resultsetGroup();
return $results;
}
This is the php code i've been trying to alter in 500 different ways, and still i cannot get the result i am after - if i do not pdo group by u.id but u.name - it works, but then again, 2 people can have the same name - and that will break my intention.
<?php var_dump($data['vacations']); ?>
<?php foreach($data['vacations'] as $key => $vac) : ?>
<?php echo $key; ?>
<?php foreach($vac as $va) : ?>
<?php echo key($vac);?>
<h1><?php echo $va['name'] ?></h1>
<?php endforeach ; ?>
<?php endforeach ; ?>
Can you pls help me out? i feel like im running around in cirkles.
enter code here
Try this:
$vacations = array();
foreach($data['vacations'] as $key => $value){
foreach($value as $index => $person){
$vacations[$person['drivernumber']] = array();
$vacations[$person['drivernumber']]['name'] = $person['name'];
$vacations[$person['drivernumber']]['drivenumber'] = $person['drivenumber'];
$vacations[$person['drivernumber']]['vacations'] = "";
}
}// With this, you will have the array $vacations with the drivernumbers as keys without duplicates and initialized the name, drivenumber and vacations string.
foreach($data['vacations'] as $key => $value){
foreach($value as $index => $person){
$vacations[$person[drivenumber]]['vacations'] += $person['period_start'] . "-" . $person['period_end'] . " ";
}
}//This will concatenate all the period_start and period_end of each person in their respective position in the array.
foreach($vacations as $key => $value){
echo $value['name'] . " " . $value['drivernumber'] . " " . $value['vacations'];
}//Finally.. print in the format that you are requesting.
Please try.

How can I filter data from my array php?

I am really struggling filtering my data.I know how to access parts of the array but am struggling on how to filter. I know how to do it in SQL SUM & count) but not when it comes to PHP arrays please help.
I need to filter some of my data stored in the variable $res.
I need to see how many times each 'REF' appears & total 'LCL_D_CBM' for each ref all of this where the "TERR" is equal to "TERR1".
foreach ($res as $res1){
if ($res1["TERR"] == "TERR1"){
//the individual ref
//$res1['REF'];
// the coutn of how many times each ref appears
//echo count($res1['REF']);
//sum
//echo array_sum($res1['LCL_D_CBM']);
}
}
need result to be like -
CEA
3
2561
CEF
456
135
var_dump($res); gives me below
array(350) {
[0]=> array(7) { [0]=> string(3) "CEA" ["REF"]=> string(3) "CEA" [1]=> string(5) "1.080" ["LCL_D_CBM"]=> string(5) "1.080" [2]=> string(3) "WF2" ["AREA_CODE"]=> string(3) "WF2" ["TERR"]=> string(5) "TERR1" }
[1]=> array(7) { [0]=> string(3) "CEA" ["REF"]=> string(3) "CEA" [1]=> string(5) "2.000" ["LCL_D_CBM"]=> string(5) "2.000" [2]=> string(4) "HU13" ["AREA_CODE"]=> string(4) "HU13" ["TERR"]=> string(5) "TERR1" }
[2]=> array(7) { [0]=> string(3) "CEF" ["REF"]=> string(3) "CEA" [1]=> string(5) "2.448" ["LCL_D_CBM"]=> string(5) "2.448" [2]=> string(4) "TW16" ["AREA_CODE"]=> string(4) "TW16" ["TERR"]=> string(5) "TERR2" } ..... etc
You can solve it like this. Not a pretty solution, but should do the work. (I did not test this, so it might contain a spelling error or something):
$sum_lcl = 0;
$unique_refs = array();
foreach ($res as $res1){
if (!array_key_exists($res1['REF'], $unique_refs)) {
$unique_refs[$res1['REF']] = array();
}
$unique_refs[$res1['REF']]['SUM'] = ( array_key_exists('SUM', $unique_refs[$res1['REF']]) ) ? ( intval( $unique_refs[$res1['REF']]['SUM'] ) + 1 ) : 1;
$unique_refs[$res1['REF']]['LCL_SUM'] = ( array_key_exists('LCL_SUM', $unique_refs[$res1['REF']]) ) ? ( floatval( $unique_refs[$res1['REF']]['LCL_SUM'] ) + floatval( $res1['LCL_D_CBM'] ) ) : 1;
}
foreach( $unique_refs AS $unique => $data ){
$title = $unique;
$sum = $data['SUM'];
$lcl_sum = $data['LCL_SUM'];
echo "{$title}<br />{$sum}<br />{$lcl_sum}";
}

Categories