This question already has answers here:
How to remove duplicate values from an array in PHP
(26 answers)
Closed 4 years ago.
I have an array and it has repeating items. So I trying to delete item if it repeats. For example:
$links:
string(35) "/mjr/semba-tower/outline/index.html"
[1]=>
string(38) "/mjr/mc-futsukaichi/outline/index.html"
[2]=>
string(31) "/mjr/chihaya/outline/index.html"
[3]=>
string(35) "/mjr/semba-tower/outline/index.html"
As you see 2 semba-towers in the array and I want to delete one of if.
I tried this, but output returns 0 item.
$output = [];
foreach(array_count_values($links) as $value => $count)
{
if($count == 1)
{
$output[] = $value;
}
}
var_dump($output);
Any other way to fix this problem?
Use the PHP array_unique() function
You can use the PHP array_unique() function to remove the duplicate elements or vlaues form an array. If the array contains the string keys, then this function will keep the first key encountered for every value, and ignore all the subsequent keys.
$links = array(
"/mjr/semba-tower/outline/index.html",
"/mjr/mc-futsukaichi/outline/index.html",
"/mjr/chihaya/outline/index.html",
"/mjr/semba-tower/outline/index.html"
);
// Deleting the duplicate items
$result = array_unique($links);
print_r($result);
OUTPUT:
Array ( [0] => /mjr/semba-tower/outline/index.html [1] => /mjr/mc-futsukaichi/outline/index.html [2] => /mjr/chihaya/outline/index.html )
Related
This question already has answers here:
Move array item with certain key to the first position in an array, PHP
(9 answers)
move array element to the first position but remain order
(4 answers)
Move an array element to a new index in PHP
(9 answers)
Move Value in PHP Array to the Beginning of the Array
(12 answers)
Move array element with a particular value to top of array
(2 answers)
Closed 2 months ago.
How to sort an array at PHP to force selected row as a first ?
My array is
array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
How to sort the array to force
array[]=array(id=>'b', content=>'apple');
as a first row and doesn't matter the rest (apple is the key).
And in other example turn sort to get
array[]=array(id=>'d', content=>'cherry');
as a first row and doesn't matter the rest (cherry is the key).
Another way to do this is to effectively rotate the array using array_slice, bringing the element you want to the start:
$first = 'apple';
$k = array_search($first, array_column($array, 'content'));
$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));
print_r($array);
Output:
Array (
[0] => Array ( [id] => b [content] => apple )
[1] => Array ( [id] => c [content] => banana )
[2] => Array ( [id] => d [content] => cherry )
[3] => Array ( [id] => a [content] => lemon )
)
Demo on 3v4l.org
There are 2 ways I can think of doing this. The first is as Ultimater in the comments suggest to extract the matching row, then sort and then add the row back in...
$first = 'apple';
$array = [];
$array[]=array('id'=>'a', 'content'=>'lemon');
$array[]=array('id'=>'b', 'content'=>'apple');
$array[]=array('id'=>'c', 'content'=>'banana');
$array[]=array('id'=>'d', 'content'=>'chery');
$firstElement = array_search($first, array_column($array, "content"));
$row = $array[$firstElement];
unset($array[$firstElement]);
sort($array);
array_unshift($array, $row);
print_r($array);
The second is to use usort and add specific clauses in that if the key matches the row you want first, then it will always force it to the first row...
$first = 'apple';
usort($array, function ($a, $b) use ($first){
if ( $a['content'] == $first) {
return -1;
}
if ( $b['content'] == $first) {
return 1;
}
return $a <=> $b;
});
print_r($array);
(I've used <=> in this which is PHP 7+, there are alternatives if you need to use PHP 5).
If as your comment suggests that there is no need to sort the rest of the data, then the first set of code minus the sort() should do.
One other option - if id:content is one to one, we can index the array by content and merge with an array with a single empty "apple" key (or whichever content value you're looking for).
$array = array_merge(['apple' => []], array_column($array, null, 'content'));
If the resulting string keys are undesirable the array can be reindexed with array_values.
If the array only contains id and content and id:content is in fact one to one, a "dictionary" of key-value pairs will be handier to deal with than a list of rows like this and it would probably be better to set the array up that way to begin with if possible.
If id:content is not one to one, then... never mind. ;-)
This question already has answers here:
How to re-index the values of an array in PHP? [duplicate]
(3 answers)
Closed 2 years ago.
I have an array
$cars = array("Volvo", "BMW", "Toyota", "Mercedes");
I wanted to remove first element "Volvo" and i use this
unset($cars[0]);
Now i have an array like this:
Array
(
[1] Bmw
[2] Toyota
[3] Mercedes
)
But i want to my array begins again with zero, to be like this:
Array
(
[0] Bmw
[1] Toyota
[2] Mercedes
)
How to do it?
Use array_values function to reset the array, after unset operation.
Note that, this method will work for all the cases, which include unsetting any index key from the array (beginning / middle / end).
array_values() returns all the values from the array and indexes the array numerically.
Try (Rextester DEMO):
$cars = array("Volvo", "BMW", "Toyota", "Mercedes");
unset($cars[0]);
$cars = array_values($cars);
var_dump($cars); // check and display the array
Use array_slice() instead that select special part of array
$newCars = array_slice($cars, 1)
Check result in demo
Assuming you always want to remove the first element from the array, the array_shift function returns the first element and also reindexes the rest of the array.
$cars = array("Volvo", "BMW", "Toyota", "Mercedes");
$first_car = array_shift($cars);
var_dump($first_car);
// string(5) "Volvo"
var_dump($cars)
// array(3) {
// [0] =>
// string(3) "BMW"
// [1] =>
// string(6) "Toyota"
// [2] =>
// string(8) "Mercedes"
//}
This question already has answers here:
Turning multidimensional array into one-dimensional array [duplicate]
(11 answers)
Closed 7 years ago.
I have an array as shown below,
How to convert the above array1 into array2 form?
array1
Array
(
[0] => Array
(
[0] => 500 GB
)
[1] => Array
(
[0] => 100 GB
)
)
array2
Array
(
[0] => 500 GB
[1] => 100 GB
)
$yourArray = [[0 => '500 GB'], [0 => '100 GB'], [1 => '200 GB']];
$result = array_filter(
array_map(
function($element) {
if (isset($element[0])) {
return $element[0];
}
return;
},
$yourArray
),
function($element) {
return $element !== null;
}
);
echo var_dump($result); // array(2) { [0]=> string(6) "500 GB" [1]=> string(6) "100 GB" }
This will work only with php >= 5.4 (because of array short syntax). If you're running on older versione, just substitute [] with array()
Explaination
array_filter is used to exclude certain values from an array (by using a callback function). In this case, NULL values that you get from array_map.
array_map is used to apply a function to "transform" your array. In particular it applies a function to each array element and returns that element after function application.
I have to insert some data from an excel document into the database.
The data has been saved as .csv and then added into an array through PHP.
The data look like:
Column A Column B Column C
100 200 100
50 10 100
200 200 100
30 10 300
Then I use this to separate each columns (within a foreach loop)
list( $columnA, $columnB) = explode( ',', $values[0] );
$columnA= array($columnA);
print_r($columnA);
The above code prints the values of each column.
So I'm trying to find a way to remove duplicates from each column and then from each row (no matter what the column name is). I want to remove duplicates from the whole document. For the data I posted for example I just need the values 100,200,50,10,30,300 (only the unique values from the whole doc).
UPDATE:
What the original array (the one I've created by using for loop and passing all data from .CSV file) shows:
Array ( [0] => G2100,100%,,,,,,,,,200,0.24,77,51,2,47, )
Array ( [0] => G2101,100%,,,,,,,,,200,0.24,77,42,15,43, )
Array ( [0] => G2102,30%,,,,,,,,,200,0.24,77,38,25,37, )
So by using the list function I mentioned before I split all columns and get the values for each column. THEN if i print $columnB array for example it shows this:
Array ( [0] => 100%) Array ( [0] => 100%) Array ( [0] => 30%)
and so on. When I use unique_array it does nothing.
$columnB = array_unique($columnB, SORT_REGULAR);
I tried to use array_map but it doesn't work either.
Any help would be much appreciated.
I don't understand why does array_unique not works in your case, because actually it solves the problem:
<?php
$columnA = array(50,50,200,10);
$columnB = array(100,50,200,100);
$columnC = array(150,50,250);
$merged = array_merge($columnA, $columnB, $columnC);
$result = array_unique($merged);
var_dump($result);
?>
And output is:
array(6) {
[0]=>
int(50)
[2]=>
int(200)
[3]=>
int(10)
[4]=>
int(100)
[8]=>
int(150)
[10]=>
int(250)
}
This is an trivial example, but if you can manage that your inputs are like arrays above, then you can use array_unique to have only unique values...
EDIT 1:
To remove % sign from string just use rtrim where is needed:
$string = '100%';
$trimmed = (int)rtrim($string,'%');//make it int(or float if you like)
var_dump($trimmed);
EDIT 2:
Related to looping through arrays:
//I suppose this
//Array ( [0] => 100%) Array ( [0] => 100%) Array ( [0] => 30%)
//maps to this
$columnA = array(
0=>array('100%'),
1=>array('100%'),
2=>array('30%')
);
//go through every element
$temp = array();
foreach($columnA as $subArray){
//in this case when we know that there is only one element in the array we can do next:
$temp[] = $subArray[0];
}
$result = array_unique($temp);
echo "<pre>";
var_dump($result);
echo "</pre>";
And this would be the output:
array(2) {
[0]=>
string(4) "100%"
[2]=>
string(3) "30%"
}
When retrieving a hierarchical structure from MySQL (table with one ID column and one PARENT column signifying the hierarchical relationships), I map the result into an enumerated array as follows (for this example the numbers are arbitrary):
Array ( [3] => Array ( [7] => Array () ), [7] => Array ( [8] => Array () ) )
Notice 3 is the parent of 7, and 7 is the parent of 8 (this could go on and on; and any parent could have multiple children).
I wanted to shrink this array into a nested multidimensional array as follows:
Array ( [3] => Array ( [7] => Array ( [8] => Array () ) ) )
That is, each NEW id is automatically assigned an empty array. Regardless, any ID's children will be pushed into their parent's array.
Take a look at the following illustration for further clarification:
alt text http://img263.imageshack.us/img263/4986/array.gif
This will probably result in a complicated recursive operation, since I always have to check whether a parent with any certain ID already exists (and if so, push the value into its array).
Is there a built-in php function that can assist me with this? Do you have any idea as to how to go about constructing this? For what it's worth I'm using this to built a navigation bar in wordpress (which can contain categories, subcategories, posts... essentially anything).
The idea is that you keep an auxiliary array with all the nodes (parent and child) you find. The values of this arrays are references that back your result.
This builds the tree in linear time (array_key_exists does a hash table lookup, which is on average O(1)):
//table contains (id, parent)
$orig = array(
11 => 8,
7 => 3,
8 => 7,
99 => 8,
16 => 8,
);
$childrenTable = array();
$result = array();
foreach ($orig as $n => $p) {
//parent was not seen before, put on root
if (!array_key_exists($p, $childrenTable)) {
$childrenTable[$p] = array();
$result[$p] = &$childrenTable[$p];
}
//child was not seen before
if (!array_key_exists($n, $childrenTable)) {
$childrenTable[$n] = array();
}
//root node has a parent after all, relocate
if (array_key_exists($n, $result)) {
unset($result[$n]);
}
$childrenTable[$p][$n] = &$childrenTable[$n];
}
unset($childrenTable);
var_dump($result);
gives
array(1) {
[3]=>
array(1) {
[7]=>
array(1) {
[8]=>
array(3) {
[11]=>
array(0) {
}
[99]=>
array(0) {
}
[16]=>
array(0) {
}
}
}
}
}
EDIT: unset $childrenTable in the end to clear reference flags. In practice, you will probably want to do the operation inside a function anyway.
This question and it's answers should be helpful to you: turn database result into array.
Be sure to read the PDF presentation by #Bill Karwin, specifically the topics regarding the Closure table.