php facebook people search how to remove repeat value? - php

https://graph.facebook.com/search?q=tom&type=user&access_token=2227470867|2.AQD2FG3bzBMEiDV3.3600.1307905200.0-100001799728875|LowLfLcqSZ9YKujFEpIrlFNVZPQ
how to avoid repeat name in facebook people search? in the json code, there have 2 Thomas Lee. Thanks.
foreach ($status_list['data'] as $data) {
echo $data['name']; // not print the same name.
}

$names = Array();
foreach ($status_list['data'] as $data) {
$names[] = $data['name'];
}
$names = array_unique($names); // not print the same name.
foreach ($names as $name) {
echo $name;
}

Here's a fast mashup of how you remove duplicates:
<?php
function existsInArray($list, $key, $value){
foreach($list as $lkey => $lvalue){
if($lvalue[$key] == $value){
return true;
}
}
return false;
}
$sortedUsers = array();
foreach($status_list['data'] as $data){
if(!existsInArray($sortedUsers, "id", $data["id"])){
$sortedUsers[] = $data;
}
}
This will go through the array och users, check if each item exist with the same id in the sorted array. If it doesn't exist, it will be added to the sorted array. Then you have $sortedUsers which doesn't contain any duplicates.
Note: However, this is just proof of concept code. So there are probably a lot of performance optimization that could be done. Also, there are probably some built in functionality to which can do this with less user defined code. Why I showed this is to just explain the process.
Edit: Since this answer got accepted I feel obligated to show something which is a little more high quality than proof of concept code. Also because it got mentioned in the comments that it was inefficient.
So here's easy fix to make this much faster:
$sortedUsers = array();
foreach($status_list['data'] as $data){
$sortedUsers[$data["id"]] = $data;
}
This way it will just overwrite the duplicates and will take away the whole process of comparing each item. In worst case this will be O(n) where as the proof of concept code was O(n ^ (n / 2)) in worst case.

Related

Seeking advice to optimize the following code chunk. (I need to avoid the IF ELSES)

I have a JSON file with around 30 sub sections. Each subsection will be different. I wanted to convert the data inside it into a format i wanted. The code works fine. But i feel its not optimized 100%.
Client1Insurance, Client2Insurance, ClientFInsurance, FamilyInsurance, Client1Pension, Client2Pension, ClientFPension, FamilyPension.
Above is an example of how this JSON would look like. All above are arrays which have sub arrays inside them. There are around 30 arrays like this.
foreach ($json as $item) {
if (strpos($crmMapKey, "Insurance")) {
$returnArray[] = $this->handleInsurance($item);
} elseif (strpos($crmMapKey, "Pension")) {
$returnArray[] = $this->handlePension($item);
} ... continues the comparison till the json ends
}
I need a way to avoid this long if else comparions which I am not proud of. Will someone be able to suggest a better way to do this?
Thanks.
If they are named the same as you show in your code, something containing Insurance will call handleInsurance, etc. then just get the term and use it in the method call:
preg_match('/Insurance|Pension/', $crmMapKey, $match);
$returnArray[] = $this->{'handle'.$match[0]}($item);
If not then you can use a lookup array:
$lookup = ['Insurance' => 'doSomething', 'Pension' => 'doAnotherThing'];
preg_match('/Insurance|Pension/', $crmMapKey, $match);
$returnArray[] = $this->{'handle'.$lookup[$match[0]]}($item);
Or use the keys in the pattern so you only have to modify the array:
preg_match('/'.implode('|', array_keys($lookup)).'/', $crmMapKey, $match);
The switch I mentioned in a comment might not be the best but works:
switch(true) {
case strpos($crmMapKey, "Insurance") !== false;
$returnArray[] = $this->handleInsurance($item);
break;
case strpos($crmMapKey, "Pension") !== false;
$returnArray[] = $this->handlePension($item);
break;
//etc...
}
Another way would be to call variable based functions.
foreach ($json as $item) {
$returnArray[] = $crmMapKey($item);
}
function Client1Insurance($item) {
// Do something in here.
return $array;
}
function Client2Insurance($item) {
// Do something in here.
return $array;
}
Much more elegant way of doing things I feel.

Restricting foreach with json to only specific field

I have this function
$url = file_get_contents('https://graph.facebook.com/search?q='.spaces($query).'&fields='.$fields.'&limit='.$limit.'&until='.$until);
$j = json_decode($url);
foreach($j->data as $v) {
}
I want to restrict th search to only those data that has as type = status.
I tried to do so:
foreach($j->data->type =='status' as $v) {
But it returns an error.
What is the easy - clean way to achieve this?
You need to iterate over all of them an check inside the loop:
foreach ($j->data as $v) {
if ($v->type == "status") {
// Do whatever you were going to do...
}
}
It is possible to use array_filter() to remove the values you aren't interested in before iterating, but probably not worth the extra effort since the performance gain would be minimal to non-existant.

How would I loop through this?

I have a large array.
In this array I have got (among many other things) a list of products:
$data['product_name_0'] = '';
$data['product_desc_0'] = '';
$data['product_name_1'] = '';
$data['product_desc_1'] = '';
This array is provided by a third party (so I have no control over this).
It is not known how many products there will be in the array.
What would be a clean way to loop though all the products?
I don't want to use a foreach loop since it will also go through all the other items in the (large) array.
I cannot use a for loop cause I don't know (yet) how many products the array contains.
I can do a while loop:
$i = 0;
while(true) { // doing this feels wrong, although it WILL end at some time (if there are no other products)
if (!array_key_exists('product_name_'.$i, $data)) {
break;
}
// do stuff with the current product
$i++;
}
Is there a cleaner way of doing the above?
Doing a while(true) looks stupid to me or is there nothing wrong with this approach.
Or perhaps there is another approach?
Your method works, as long as the numeric portions are guaranteed to be sequential. If there's gaps, it'll miss anything that comes after the first gap.
You could use something like:
$names = preg_grep('/^product_name_\d+$/', array_keys($data));
which'll return all of the 'name' keys from your array. You'd extract the digit portion from the key name, and then can use that to refer to the 'desc' section as well.
foreach($names as $name_field) {
$id = substr($names, 12);
$name_val = $data["product_name_{$id}"];
$desc_val = $data["product_desc_{$id}"];
}
How about this
$i = 0;
while(array_key_exists('product_name_'.$i, $data)) {
// loop body
$i++;
}
I think you're close. Just put the test in the while condition.
$i = 0;
while(array_key_exists('product_name_'.$i, $data)) {
// do stuff with the current product
$i++;
}
You might also consider:
$i = 0;
while(isset($data['product_name_'.$i])) {
// do stuff with the current product
$i++;
}
isset is slightly faster than array_key_exists but does behave a little different, so may or may not work for you:
What's quicker and better to determine if an array key exists in PHP?
Difference between isset and array_key_exists

php Removes duplicate values in foreach

I have a foreach iterator, there are 500 group items in it. How do I remove duplicate values in a foreach?
foreach ($data as $data) {
if(!empty($data['name'])){ //check if have $data['name']
$name = $data['name'];
$id = $data['id'];
$date = $data['date'];
$link = $data['link'];
if(strpos($link, '.ads.')){
continue; //remove all the link contains `.ads.`
}else{
// if `$link` is not repeat, echo the below data. how to use array_unique, remove all the values which repear in `$link` part?
echo $name;
echo $id;
echo $date;
echo $link;
}
}
With array_unique:
foreach (array_unique($data) as $d) {
// Do stuff with $d ...
}
Although you can technically call the array and its elements by the same name, it's bound to lead to programming errors and confusion afterwards.
Look what you do:
foreach ($data as $data)
You are overwriting the contents of $data, then you access $data while you expect it still to be the original array. That's just wrong.
Take an additional variable name, pretty common is $value:
foreach ($data as $value)
Hope this helps even if it is not answering your question, but this can be part of your problem, so take care ;)
$fetch=$q->result();
$array_result= json_decode(json_encode($fetch), true);
$g=array();
foreach($array_result as $p)
{
array_push($g,$p['email']);
}
$array=array_values(array_filter(array_unique($g)));
I was using this when i had o choose unique e-mail id's out of a number of similar emails which was coming via Ajax response...hope this helps u can ask queries if u do hv problem understanding anywhere..

Patterns for building multidimensional array with unique key

Problem:
Extract data from an object/array and represent this data using a multidimensional array with a unique key generated from the inner loop.
I always find myself building multidimensional arrays like this:
$final_array = array();
foreach ($table as $row) {
$key = null;
$data = array();
foreach ($row as $col => $val) {
/* Usually some logic goes here that does
some data transformation / concatenation stuff */
if ($col=='my_unique_key_name') {
$key = $val;
}
$data[$col] = $val;
}
if (!is_null($key) {
if (!isset($final_array[$key]) {
$final_array[$key] = array();
}
$final_array[$key][] = $data;
}
}
I can't help but wonder if I'm constantly doing this out of habit, but it feels kind of verbose with all the key-checking and whatnot. Is there a native function I am not utilizing? Can this be refactored into something more simple or am I overthinking this?
Why are you always doing that? Doesn't seem the common kind of stuff one works with on a day to day basis... Anyway, that's kinda cryptic (an example would be nice) but have you though of using an MD5 hash of the serialized dump of the array to uniquely define a key?
$key = md5(serialize($value));

Categories