How to search array for duplicates using a single array? - php

I am checking a list of 10 spots, each spot w/ 3 top users to see if a user is in an array before echoing and storing.
foreach($top_10['top_10'] as $top10) //loop each spot
{
$getuser = ltrim($top10['url'], " users/" ); //strip url
if ($usercount < 3) {
if ((array_search($getuser, $array) !== true)) {
echo $getuser;
$array[$c++] = $getuser;
}
else {
echo "duplicate <br /><br />";
}
}
}
The problem I am having is that for every loop, it creates a multi-dimensional array for some reason which only allows array_search to search the current array and not all combined. I am wanting to store everything in the same $array. This is what I see after a print_r($array)
Array ( [0] => 120728 [1] => 205247 ) Array ( [0] => 232123 [1] => 091928 )

There seems to be more to this code. As there are variables being called in it that aren't defined, such as $c, $usercount, etc.. And using array_search with the 2nd parameter of $array if it doesn't exist is not a good idea also. Since it seems like $array is being set within the if statement for this only.
And you don't seem to be using the $top10 value within the foreach loop at all..., why is this?
It would help to see more of the code for me to be able to help you.

Related

php- popping a value from array returns wrong result

Ok, I will explain what I am trying to implement here. It's like a number search. I will pass a number and server returns an array of all number. If the passed number is present, I will have to pop that number from the array.
It works, but not in all scenarios.
<?php
function fetchAll()
{
$data= array();
$motherArray='["1","48","2","44","4"]';
$data = json_decode($motherArray);
return $data;
}
$allIDs=fetchAll();
if (!empty($allIDs))
{
$checkThis=4;
if(in_array($checkThis,$allIDs))
{
if (($key = array_search($checkThis, $allIDs)) !== false)
{
unset($allIDs[$key]);
}
if(!empty($allIDs))
{
$allIDsJSON = json_encode($allIDs);
echo $allIDsJSON;
}
else
{
echo 'empty';
}
}
else
{
echo 'not present';
}
}
?>
Above given is my code. I'm trying to search for the number 4.
Number 4 can be in any position. It can be in first, middle or the last. My code works if the number is in last position. Then, it returns the correct output.
Case 1:
$motherArray='["1","48","2","44","4"]';
if it is in last position, I get the correct output:
["1","48","2","44"]
Case 2:
If number 4 is in any other position
$motherArray='["1","48","2","4","44"]';
then the output I get is:
{"0":"1","1":"48","2":"2","4":"44"}
I don't know why it is happening like that.
Can anyone help me figure out what's wrong with this code?
You're code won't work if there is multiple value of your number:
foreach (array_keys($allIDs, $checkThis) as $key)
unset($allIDs[$key]);
The correct answer is provided in the comments already.I will just add it here with some explanation.
If number is not in last position then when you unset($allIDs[$key]); you create an array that is not sequential.
Original array:
Array ( [0] => 1 [1] => 48 [2] => 2 [3] => 4 [4] => 44 )
Array after unsetting third element: Array ( [0] => 1 [1] => 48 [2] => 2 [4] => 44 )
Because in javascript there are not associative arrays when you use json_encode($allIDs); the valid JSON result you get is a JSON object not an array.
So if you want an array you have to reindex the array yourself like that:
$indexed_array = array();
foreach ($allIDs as $row) {
$indexed_array[] = $row;
}
json_encode($indexed_array);
Or by using array_values function
echo json_encode(array_values($allIDs))

Breaking a MultiDimensional Array into a Single Dimension

I have fields in mySQL which is currently being stored like this under the field "tags"
Shopping|Health & Beauty
Coffee|Shopping
What I'm trying to do is to loop through this to create a single dimension array and to grab only the unique values.
I have my query selecting DISTINCT tags from TABLE and run the loop like this:
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
}
echo "<pre>";
print_r($imploded_tags);
The result from the print_r is showing it as a multidimensional array. I've tried to reexplode it and implode it in different ways, but I haven't been able to get any success. Is there a way that I can create this into a single dimension array? Not all tags will have an equal amount of tags separated by |, so I can't seem to get it to go with a function that I tried from another StackOverflow post. Any help would be greatly appreciated!
OUTPUT:
Array
(
[0] => Array
(
[0] => Shopping
[1] => Health & Beauty
)
[1] => Array
(
[0] => Coffee
[1] => Shopping
)
try this
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$tags = explode("|",$tags);
foreach($tags as $v){
$imploded_tags[] = $v;
}
}
I would do something like:
$imploded_tags = array_merge(explode("|",$tags), $imploded_tags);
}
$imploded_tags = array_unique($imploded_tags);
echo "<pre>";
print_r($imploded_tags);
See the manual on array_merge and array_unique.
However, I do think you are not using the right way to store your tags; they should be stored in a separate table as separate values.
What's going on is when you're fetching your rows from MySQL, you're essentially getting a bunch of data in an array in the first place, which is why you have to loop through them.
With your your implode function, you're taking a bunch of strings, then getting another array set and then appending that to an external array.
If you really wanted to get a single dimensional array without having this multidimensional thing going on, all you really need to do is utilize another loop within that loop.
$all_tags = array();
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
for($i = 0; $i < count($imploded_tags); $i++) {
$all_tags[] = $imploded_tags[$i]
}
}
print_r($all_tags);

How to detect duplicate php Array

I have this array:-
Array ( [0] => Prefectorial Board/Prefect/2011 [1] => Prefectorial Board/Head Prefect/2011 [2] => Class Positions/Head Prefect/2011 [3] => Prefectorial Board/Head Prefect/2011 )
How to detect this array have duplicate value and I want the participant to re-fill in his data.
I have try to use this method to detect:-
$max = max(array_values($lr_str));
$keys = array_keys($lr_str, $max);
but it seem like not work for me.
any idea on this?
thanks for advance.
I do not know if I understand you correctly, but you can test the array has duplicated values by using this:
if (count($your_array) === count(array_unique($your_array)) {
// array has no duplicated values
} else {
// array has duplicated values - see compared arrays
}
Are you looking for array_unique?
You can use array_unique() to remove duplicate values. If no values were removed then the returned array should have the same number of items as the original:
if(count($lr_str) == count(array_unique($lr_str))){
//tell participant to re=fill their data
}

While loop in foreach loop not looping correctly

I'm trying to make a very basic php ORM as for a school project. I have got almost everything working, but I'm trying to map results to an array. Here's a snippet of code to hopefully assist my explanation.
$results = array();
foreach($this->columns as $column){
$current = array();
while($row = mysql_fetch_array($this->results)){
$current[] = $row[$column];
print_r($current);
echo '<br><br>';
}
$results[$column] = $current;
}
print_r($results);
return mysql_fetch_array($this->results);
This works, but the while loop only works on the first column. The print_r($results); shows the following:
Array ( [testID] => Array ( [0] => 1 [1] => 2 ) [testName] => Array ( ) [testData] => Array ( ) )
Can anybody shed some light?
Thanks in advance!
It's because you already fetched every row, and the internal pointer is at the end.
The next while, mysql_fetch_array() will immediately return false.
You can reset the pointer to the first row:
mysql_data_seek($this->results, 0);
Put this just before
while($row = mysql_...
I'm not sure you can use the -> operator in a variable name. As you trying to get the key and value out of the array $columns? If so, you want something like this:
foreach($columns as $k => $v) {
//in here, $k is the name of the field, and $v is the associated value
}

foreach loop corrupting my array?

Explanation
I have a multidimensional array that is iterated over to created a categorized view of people with different research interests. The main array look something like this:
Array
(
...
['Cell Biology'] => Array(4 elements)
['Molecular'] => Array(6 elements)
['Biology Education'] => Array(14 elements)
['Plant Biology'] => Array(19 elements) <--- Last element in array
)
I know that the entire array is intact and correctly structured. The only information that is inside these array is an user id, like so:
Array ('Plant Biology') 19 elements
(
[0] => 737
[1] => 742
[2] => 748
...
)
My problem is that after i run the main array through a foreach loop the last 'sub-array' gets messed up. By messed up I mean that what you see about instead look like:
String (13 characters) 'Plant Biology'
This is without doing at all anything inside the loop with to the array that gets corrupted.
Any tips to what it might be?
PHP Code
// ---> Array is OK here
echo "<h2>Research divided</h2>";
// Loop areas and list them in 2 columns
foreach($research['areas'] as $area => $areaArray) {
// ---> Here it is already corrupted
$count = count($areaArray);
if($count > 0) {
echo "<h3>$area</h3><hr/>";
echo "<ul>";
// Loop users within areas, divided up in 2 columns
for($i=0 ; $i<$count ; $i++) {
$uid = $areaArray[$i];
echo "<li>$uid</li>";
}
echo "</ul>";
}
}
Are $area or $areaArray being used in different function elsewhere in your script? Wht happens if you rename them to $loop_area and $loop_areaArray to prevent accidental overwriting of variables?
It looks like an error that can occur if you loop over the array previously by referance using the same variable name for the value.
So if earlier in your code $areaArray is used in a foreach by referance it might corrupt your data.
Make sure both variables in your foreach are not used previously or unset them before the loop.
Check out:
http://bugs.php.net/29992
For more info on this kind of problem.

Categories