Remove duplicate values from Array - php

I can not "remove" the double values ​​from an array even if I use the function array_unique!
<?php
$tags_array = array() ;
$query_tags = $mysql->Query("SELECT words AS kw FROM users ") ;
/****
*
* This query return something like Array([1] => PHP,ASP,NET [2] => Ruby,Jquery,php,asp_net [3] => Php,asp,visualbasic,c# [4] => [5] =>)
*
*****/
while($fetch_tags = $mysql->Fetch($query_tags))
{
foreach(explode(',',$fetch_tags['kw']) as $kw => $value)
{
if(empty($value)) ;
else
{
$value = ucwords(strtolower($value)) ;
$tags_array[] = $value ;
}
}
}
$tags_array = array_values(array_unique($tags_array, SORT_STRING)) ;
print_r($tags_array) ;
/******
*
* print_r show somethings like this Array([1] => Asp [2] => Php [3] => Php [4] => Ruby [5] => Jquery [6] => Php [7] => Asp_net [8] = >C# [9] => Asp)
*
* IT'S ONLY AN EXAMPLE TO SHOW YOU THE SITUATION
*****/
?>

Make sure that the returned values are in fact not unique. For example
$foo = array("PHP","php","pHP","PHP ");
$foo = array_unique($foo);
Will still contain 4 entries.
If any entries contain spaces you should trim these.

Just use values as keys, they can only exist once and you don't have any numbers as your keywords (hopefully):
$tags_array = array_keys(array_flip(($tags_array));
array_flip will use values as keys (and drop duplicate values) and array_keys will then return all keys as values again.

Given that is the only thing that aray_unique is supposed to do, I find it very surprising it's not doing it. What is apparent from your post, is that maybe you think 'php' is the same thing as 'PHP'?
When I try the following I get unique results:
$d=Array('PHP,ASP,NET','Ruby,Jquery,php,asp_net','Php,asp,visualbasic,c#');
$o=array();
foreach ($d as $i) {
$p=explode(',',$i);
foreach ($p as $q) {
$o[]=strtoupper($q);
}
}
print_r(array_unique($o));
However the issue only arises because your database schema is not normalised.

As no one seemed to have provided the right answer, I'll repeat my comment here:
It might be that the words have preceding or trailing white spaces. Then they will never be equal to each other. You can remove these white spaces with trim [docs]
$value = ucwords(strtolower(trim($value)));

Related

Create PHP Variables dynamically in foreach loop

I am just trying to create PHP variables dynamically. below is the code I have tried.
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
while
$BrickTerritorys is
[1] => stdClass Object
(
[id] => 119
[TerritoryID] => HYD-2-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 40.00
[BPCode] => bp00066
[GroupCode] => CMD
)
[2] => stdClass Object
(
[id] => 36330
[TerritoryID] => HYD-1-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 60.00
[BPCode] => bp00066
[GroupCode] => CMD
)
When I print in the last, nothing gets printed. Any help is much appreciated, please.
Thanks in advance
${"T$index"} as well as ${"Weightage$index"}
you don't need the dot,or you can use ${'T' . $index}. look at the dot. it's not addition operation while it in "". following this code:
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
Try changing those lines like this:
${"T$index"}= $BrickTerritory->TerritoryID;
${"Weightage$index"} = $BrickTerritory->Weightage;
In your code ${"$T.$index"} $T is searching for variable, and you should get undefined variable $T, so you have to remove $ sign, if you want to have T1, T2 variables.
After that, ${"'Weightage'.$index"}, the apostrophes between Weightage means your variable will look like 'Weightage'.1, 'Weightage'.2.. and etc.
This can be done a few different ways without variable variables AND produce a completely dynamic outcome.
Here's one: (Demo)
$array = (array)$BrickTerritorys; // cast as array
$tids = array_column($array, 'TerritoryID'); // isolate column data
$was = array_column($array, 'Weightage'); // isolate column data
$merged = array_merge($tids, $was); // add 2nd array data after 1st array data
foreach ($merged as $i => $v) {
echo str_repeat('-', $i) , $v; // increase hyphens on each iteration starting from 0
}
Output: (notice, no hardcoded echo)
HYD-2-CMD-HYD-1-CMD--40.00---60.00

PHP Getting a value out of an array

I have the following array extracted from a CSV file.
$line = Array (
[0] => First
[1] => Last
[2] => 102338100053
[3] => https://url.com/SKnuDbowTveUsHXwMAnixg?t=kIMVJtQ
[4] => 48a9ee0d-ba30-4ef7-94b0-75f03009e2c6
[5] => 1436.75
[6] => 21.55125
)
I am trying to get the value of [2]
I extract it like this
$number2 = $line[2];
This is fine. I get the following response. 102338100053
When I try to extract the first 6 numbers from the variable using
$Identifier = substr($number2 ,0,6)
I only get 2 numbers: 10
if I use 12
$siteIdentifier = substr($number2 ,0,12)
I get: 102338
I found this confusing so I checked the variable with urlencode
echo urlencode($number2);
This is what I received: %001%000%002%003%003%008%001%000%000%000%005%003%00
I need to get just the number and I dont know what to do to get it, as I am searching for this in a database and its not finding it?
Can someone please assist?
You may try using gettype() which gives you the datatype of your variables. Then the rest must be pretty simple to understand. I used $i<6 condition because you've mentioned you want only the first six integers.
$i= 0;
foreach($line as $key => $value){
if(gettype($value) == integer){
if($i<6){
$ints[$i] = $value;
$i++;
}
}
}

php array value repeated for each key

I have an multidimensional array made from database query and is like that:
Array
(
[0] => Array
(
[0] => -8.63296022565696
[x] => -8.63296022565696
[1] => 41.1584289069069
[y] => 41.1584289069069
[2] => 0
[seq] => 0
[3] => 2
[seq2] => 2
[4] => -8.63306031211831
[next_x] => -8.63306031211831
[5] => 41.1584543235506
[next_y] => 41.1584543235506
[6] => -8.64195115878864
[alert_x] => -8.64195115878864
[7] => 41.1599295066425
[alert_y] => 41.1599295066425
[8] => 54e728edafac1
[route] => 54e728edafac1
[9] => 54e728edafac1
[routeid] => 54e728edafac1
[10] => 2
[counttargetinter] => 2
[11] => passeio
[type] => passeio
[12] => 1355
[arcid] => 1355
)
All the values are repeated because have a key number and a key name.
Example: The value '-8.63296022565696' are in key "0" and "X".
How I can remove the duplicated?
This is how i made the array:
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_array($startRows)) {
$startInfo[] = $list;
}
Of course you can't mess with the generate JSON string to deal with the dups. You solve it during the creation of the array itself before encoding. Looking at the structure, this seems to be the problem of fetching both numeric and column indices.
Since you haven't posted any codes related to actually creating this JSON string, just use this basic idea on how to get rid of them.
If you intent do remove those numeric indices, you'll probably need to use fetch_assoc() flavours of your database API, so that in turn, you'll only get the column name indices instead of having them both.
Here's the idea:
$data = array(); // initialization of the container
while($row = your_fetch_assoc($result)) { // use assoc() instead to exclude those numeric indices
$data[] = $row;
}
echo json_encode($data);
Depending on what API you're using, if its PDO, either use -->fetch(PDO::FETCH_ASSOC) or just ->fetchAll(PDO::FETCH_ASSOC) without the need of a loop. If its MySQLi, then just use ->fetch_assoc()
EDIT: At last your codes, as I have suspected you're using _array() function which results associative and numeric indexed rows.
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_assoc($startRows)) {
$startInfo[] = $list;
}
Use pg_fetch_assoc() instead of _array() so that you'll get the associative indices only.
Like Ghost:
You can use pg_fetch_row() to get numeric indices or pg_fetch_assoc() to get field name.
$query = "SELECT * FROM foo;";
$startRows = pg_query($connection, $query);
$startInfo = array();
while($list = pg_fetch_row($startRows)) {
$startInfo[] = $list;
}
Try this:
foreach($walkroute as $routepoints){
foreach($routepoints as $key => $value){
if (is_int($key)){
unset($routepoints[$key]);
}
}
}
You have to modify it due to the fact that i don't know, what the structure and names of your array actually are.

PHPEXCEL : php excel only show 1 letter

Please help me on the PHPEXCEL. it shows only one letter.
this is my php code:
$sql_question = "SELECT * FROM tna_question WHERE title_id = '$tid' ORDER BY section_id";
$result_question = mysql_query($sql_question, $db);
$category = array();
while ($row = mysql_fetch_assoc($result_question)) {
$arr1 = $row['question'];
$arr = array_push($category ,$arr1);
$category_count++;
}
$arr3[] = $category;
the result from the sql query is an array:
Array ( [0] => gfhgfh [1] => gfhfg [2] => fggfdg [3] => fds [4] => asd [5] => fghgfh [6] => Policy Wordings / Coverage [7] => Risk Assessment / Survey & Underwriting [8] => Policy Wordings / Coverage [9] => Risk Assessment / Survey & Underwriting )
when i use this line:
$objPHPExcel->setActiveSheetIndex()->fromArray($category, NULL, 'C7');
it gives me only the first letter from each row
but if i make this one:
$objPHPExcel->setActiveSheetIndex()->fromArray($arr3, NULL, 'C7');
it'll give all the data in one row.
but The output that i want is like this:
You can use the below code to get the desired result :
foreach($arr3 as $k => $v){
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $k, $v);
}
Note : Changing the column value will make it go left and right only. In case you want to shift the entire thing down then replace $k by $k+$val where $val is the number of rows you want to shift down.

PHP Regex removing unwanted values from pattern

I have a large array of scraped names and prices similar to the following:
Array([0] => apple3 [1] => £0.40 [2] => banana6 [3] => £1.80 [4] => lemon [5] => grape [6] => pear5 [7] => melon4 [8] => £2.32 [9] => kiwi [10] => £0.50)
I would like to remove the fruit names that are not immediately followed by a price. In the above example this would remove: [4] => lemon [5] => grape [6] => pear5 resulting in the following output:
Array([0] => apple3 [1] => £0.40 [2] => banana6 [3] => £1.80 [7] => melon4 [8] => £2.32 [9] => kiwi [10] => £0.50)
If the array needs to be converted to a string in order for me to do this that is not a problem, nor is adding values between the array items in order to aid with regex searches. I have so far been unable to find the correct regular expression to do this using preg_match and preg_replace.
The most important factor is the need to maintain the sequential order of the fruits and prices in order for me at a later stage to convert this into an associative array of fruits and prices.
Thanks in advance.
Why involve regular expressions? This is doable with a simple foreach loop wherein you iterate over the array and remove names that follow names:
$lastWasPrice = true; // was the last item a price?
foreach ($array as $k => $v) {
if (ctype_alpha($v)) {
// it's a name
if (!$lastWasPrice) {
unset($array[$k]); // name follows name; remove the second
}
$lastWasPrice = false;
}
else {
// it's a price
$lastWasPrice = true;
}
}
The following code does both of your tasks at once: getting rid of the fruit without value and turning the result into an associative array of fruits with prices.
$arr = array('apple', '£0.40', 'banana', '£1.80', 'lemon', 'grape', 'pear', 'melon', '£2.32', 'kiwi', '£0.50' );
preg_match_all( '/#?([^£][^#]+)#(£\d+\.\d{2})#?/', implode( '#', $arr ), $pairs );
$final = array_combine( $pairs[1], $pairs[2] );
print_r( $final );
First, the array is converted to a string, separated by '#'. The regex captures all groups of fruits with prices - each stored as a separate subgroup in the result. Combining them into an associative array is a single function call.
Something like this might help you
$array = ...;
$index = 0;
while (isset($array[$index + 1])) {
if (!is_fruit($array[$index + 1])) {
// Not followed by a fruit, continue to next pair
$index += 2;
} else {
unset($array[$index]); // Will maintain indices in array
$index += 1;
}
}
Not tested though. Also, you need to create the function is_fruit yourself ;)
Without reformatting it, I don't think you can do it with preg_match or preg_replace-- maybe, but nothing is coming to mind.
What is creating that array? If possible, I would alter it to look more like:
Array([apple] => £0.40 [banana] => £1.80 [lemon] => [grape] => '' [pear ] => '' [melon => £2.32 [kiwi] => £0.50)
Then array_filter($array) is all you'd need to clean it up. If you can't alter the way the original array is created I'd lean towards creating key/value array out of the original.
Try replacing the pattern ** => ([a-zA-Z])** with ** => £0.00 $1**
Basically searching for the context where there is null price and inserting zero pounds.
Hope this helps.
Good luck
Simply do this :
<?php
for($i=0;$i<count($my_array);$i++)
{
if($my_array[$i+1]value=="")
unset($my_array[$i])
}
?>
assume $a is your array.
function isPrice($str) {
return (substr($str, 0, 1) == '£');
}
$newA = array();
for($i=0;$i<count($a);$i++) {
if( isPrice($a[$i]) != isPrice($a[$i+1]) ){
$newA[] = $a[$i];
}
}

Categories