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..
Related
I have a two questions with a symfony's project.
My first one :
I am trying to modify some data in an array.
I have this code
var_dump($results); // FIRST ONE
foreach ($results as $result) {
foreach ($result as $res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
var_dump($res); // THIS ONE IS MODIFIED
}
}
var_dump($results); // LAST ONE... SAME AS THE FIRST ONE
I don't understand why my array ' $results ' is no updated... am i missing something ?
And my second question : is there any way to simplify this code ? I don't like the 3 foreach.
Thanks you guys :)
PHP foreach copy each item when iterate so $result array will not update when you change $res item.
1) You can use array keys to change main array
foreach($arrr as $k => $item) {arrr[$k]['key'] = 'changed'}
2) Or you can get link to the $res item and change it dirrectly
foreach($arrr as &$item) {$item['key'] = 'changed'}
Note that second case can cause different issues
Unless you're passing an object in PHP, PHP does not pass values by reference. $res is a copy of the value, not a link to the original value. If you know what you're doing, you can pass by reference. When passing by reference, altering $res would alter the original data. You pass by reference by prefixing a & to the variable or argument.
Since this is a nested foreach, you'll also have to pass $result by reference to avoid that being a copy of the item of $results.
foreach ($results as &$result) {
foreach ($result as &$res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
}
}
I have the below code
$student_IT_vitipare = mysql_query("SELECT * from notat where dega='teknologji informacioni' AND viti_lendes='viti pare' ");
$vekt_stud_IT_vitipare = array();
while ($kolo1 = mysql_fetch_array($student_IT_vitipare)) {
$vekt_stud_IT_vitipare[] = $kolo1;
}
$gjatesia_vektorit = count($vekt_stud_IT_vitipare);
EXAMPLE: Array take from database name,last name and it has {john,trevis}{george,trolus} {dionis,karrblus} etc...
I know that if i want to echo out only name the code is :
for($i=0;i<$gjatesia_vektorit;i++){
echo $vekt_stud_IT_vitipare[$i]['name'];
}
i've tryed $vekt_stud_IT_vitipare[$i]['name']['last name']; but it does not work
you should stop using mysql_* because it's removed on php 7.0 instead use mysqli_* or PDO
your code won't work but instead if you do something like
for($i=0;i<$gjatesia_vektorit;i++){
echo $vekt_stud_IT_vitipare[$i][$i];
}
it would but you will only one value
instead you need a nested foreach loop
foreach($vekt_stud_IT_vitipare as $key => $value) {
foreach ($value as $val) {
echo $val;
}
}
Share the exact sample array which you want to compare. I will try to solve the problem. The one you shared is not sufficient.
The below array sample i need:
$vekt_stud_IT_vitipare
i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.
Is it possible to have an AND in a foreach loop?
For Example,
foreach ($bookmarks_latest as $bookmark AND $tags_latest as $tags)
You can always use a loop counter to access the same index in the second array as you are accessing in the foreach loop (i hope that makes sense).
For example:-
$i = 0;
foreach($bookmarks_latest as $bookmark){
$result['bookmark'] = $bookmark;
$result['tag'] = $tags_latest[$i];
$i++;
}
That should achieve what you are trying to do, otherwise use the approach sugested by dark_charlie.
In PHP 5 >= 5.3 you can use MultipleIterator.
Short answer: no. You can always put the bookmarks and tags into one array and iterate over it.
Or you could also do this:
reset($bookmarks_latest);
reset($tags_latest);
while ((list(, $bookmark) = each($bookmarks_latest)) && (list(,$tag) = each($tags_latest)) {
// Your code here that uses $bookmark and $tag
}
EDIT:
The requested example for the one-array solution:
class BookmarkWithTag {
public var $bookmark;
public var $tag;
}
// Use the class, fill instances to the array $tagsAndBookmarks
foreach ($tagsAndBookmarks as $bookmarkWithTag) {
$tag = $bookmarkWithTag->tag;
$bookmark = $bookmarkWithTag->bookmark;
}
you can't do that.
but you can
<?php
foreach($keyval as $key => $val) {
// something with $key and $val
}
the above example works really well if you have a hash type array but if you have nested values in the array I recommend you:
or option 2
<?php
foreach ($keyval as $kv) {
list($val1, $val2, $valn) = $kv;
}
No, but there are many ways to do this, e.g:
reset($tags_latest);
foreach ($bookmarks_latest as $bookmark){
$tags = current($tags_latest); next($tags_latest);
// here you can use $bookmark and $tags
}
No. No, it is not.
You'll have to manually write out a loop that uses indexes or internal pointers to traverse both arrays at the same time.
Yes, for completeness:
foreach (array_combine($bookmarks_latest, $tags_latest) as $bookm=>$tag)
That would be the native way to get what you want. But it only works if both input arrays have the exact same length, obviously.
(Using a separate iteration key is the more common approach however.)
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.