find non duplicated item in an array - php

I have two arrays built from different directories that contain file names stripped of extensions. I want to find the ones that don't make a pair thus I merged the array to obtain the array below. How can I find the only non duplicate item in an array?
Array
(
[0] => dbbackup_2014.09.03_07_06_27
[1] => dbbackup_2014.09.03_07_07_08
[2] => dbbackup_2014.09.03_07_13_33
[3] => dbbackup_2014.09.03_07_15_24
[4] => dbbackup_2014.09.03_07_21_57
[5] => dbbackup_2014.09.03_07_22_11
[6] => dbbackup_2014.09.03_08_40_35
[7] => dbbackup_2014.09.03_08_41_36
[8] => dbbackup_2014.09.03_08_43_38
[9] => dbbackup_2014.09.04_04_59_08
[10] => dbbackup_2014.09.03_07_06_27
[11] => dbbackup_2014.09.03_07_07_08
[12] => dbbackup_2014.09.03_07_13_33
[13] => dbbackup_2014.09.03_07_15_24
[14] => dbbackup_2014.09.03_07_21_57
[15] => dbbackup_2014.09.03_07_22_11
[16] => dbbackup_2014.09.03_08_40_35
[17] => dbbackup_2014.09.03_08_41_36
[18] => dbbackup_2014.09.03_08_43_38
)
Note: it is [9]

$a = array_flip(array_filter(array_count_values($a),function($item){
return $item == 1 ? true : false;
}));
print_r($a);
Output
Array
(
[1] => dbbackup_2014.09.04_04_59_08
)
Ideone

foreach($array as $data)
{
$values=explode("_",$data);
$output[$values[1]]++;
}
foreach($output as $date=>$number)
{
if($number==1)
echo $date;
}
Output:
2014.09.04
Fiddle

Related

I want all arrays data in one array in php

I want all arrays data in one array not all arrays in one array only the data of all arrays in one array without any other array in php. I have tried to do too many things but still don't work for me.
I also tried
json_encode
with
preg_match
But still don't work for me.
Here is my code
function fetchHashtags($getData){
$body = $getData;
$hashtag_set = [];
$array = explode('#', $body);
foreach ($array as $key => $row) {
$hashtag = [];
if (!empty($row)) {
$hashtag = explode(' ', $row);
$hashtag_set[] = '#' . $hashtag[0];
}
}
print_r($hashtag_set);
}
Output
Array
(
[0] => #Residência
[1] => #architecture
[2] => #casanaserra
[3] => #mountainhouse
[4] => #interiores
[5] => #decoration
[6] => #casanaserra
[7] => #casadecampo
[8] => #construção
[9] => #exterior
[10] => #rustico
[11] => #arpuro
[12] => #home
[13] => #riodejaneiro
[14] => #construir
[15] => #casasincriveis
[16] => #outdoor
[17] => #arquiteto
[18] => #casasincriveis
[19] => #montanhas
[20] => #archdaily
[21] => #architecturelovers
[22] => #arqlovers
[23] => #arqlove
[24] => #homedesign
[25] => #arquiteturaedecoração
)
Array
(
[0] => #We
[1] => #ascaspenvswheaton
)
Array
(
[0] => #شجریان_بشنویم...
[1] => #۰
[2] => #شجریان_بشنویم
[3] => #_
[4] => #شجریانیها
[5] => #همایون_شجریان
[6] => #مژگان_شجریان
[7] => #پرویزمشکاتیان
[8] => #موزیک
[9] => #سهراب_پورناظری
[10] => #محمدرضا_شجریان
[11] => #موزیک_ویدیو
[12] => #ایران
[13] => #ترانه_ماندگار
[14] => #تصنیف
[15] => #آهنگ_ایرانی
[16] => #هنر
[17] => #موسیقی_ایرانی
[18] => #شعروشاعری
[19] => #موسیقی_سنتی_ایران
[20] => #آواز_سنتی
[21] => #قدیمیها
[22] => #دلشدگان
[23] => #دلنشین
[24] => #سینما
[25] => #homayoun_shajarian
[26] => #music
[27] => #mohamadrezashajarian
[28] => #home
[29] => #iran
[30] => #shajarian
)
And one more thing i also want to remove some data that don't look like hashtags.
for example:
Array
(
[0] => #Residência
[1] => architecture // This should be removed
[2] => #casanaserra
[3] => mountainhouse // This also should be removed
[4] => #interiores
)
As you can see from my code you can use array_merge for merge arrays then use array_filter for filter value without # or other rules you need:
$array = [['1', '#2', '3', '#4'], ['5', '#6']];
$flatArray = array_merge(...$array);
$filteredArray = array_filter($flatArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
print_r($filteredArray);
Result:
Array (
[1] => #2
[3] => #4
[5] => #6 )
Reference:
array_merge
array_filter
str_contains
After seeing your code and the context of the situation I changed things:
Instead of use explode i used preg_split for split \n and space;
Delete array_map because you don't need it.
$array = ["
My name is Faraz shaikh i am a php developer and this my #instagram profile.Check out my #merge and my #packages with new #hashtags
#chinese #art #colors #home #harmory #peace #handmade #paintings #etsy
", "
My name is Hunain shaikh i am a php developer and this my #Facebook profile.Check out my #Berge and my #Hackages with new #tags
#english #Kite #colours #me #memory #pee #made #paints #etsafsy
"];
function fetchHashtags($getData) { // This Functions takes out the hashtags from the string and put it in to arrays.
$body = $getData;
$hashtag_set = [];
$array = preg_split('/[\s]+/', $body);
$mapArray = array_map(function($a) {
return str_replace(' ', '', $a);
}, $array);
$filteredArray = array_filter($mapArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
return $filteredArray;
}
$recentNumberOfPosts = 1;
$zeroPost = 0; //Get Post from 0 to recentNumberOfPosts | NOTE: default = 4
$finalArr = [];
while ($zeroPost <= $recentNumberOfPosts) {
// fetchHashtags($hashtagRecent['data'][$zeroPost]['caption']);
$finalArr[] = fetchHashtags($array[$zeroPost]);
$zeroPost++;
}
print_r(array_merge(...$finalArr));
Fiddle

Reorganise array, move indexes to specific locations php

I have an arbitrary number of arrays all containing the same format of data. There are 2 separate for loops looping through two separate SQL query results and adding them to 2 separate arrays.
Once I have all the information in both arrays, I am walking through them and joining them together to make a longer array.
However, as I am writing this array to a csv file, The information needs to be in order in the array so it writes it in order to the csv file. How can I do this?
Array 1
[1] => Array
(
[0] => 2017-07-21 00:00:00
[1] => Foo
[2] => Bar
[3] => 32.63
[4] => 18.36
[5] => 98.46
)
[2] => Array
(
[0] => 2017-07-21 00:00:00
[1] => Foo
[2] => Bar
[3] => 29.74
[4] => 148.68
[5] => 178.42
)
//etc
Array 2
[1] => Array
(
[0] => RTGH707321222
[1] => THIS
[2] => IS
[3] => TEXT
)
[2] => Array
(
[0] => RTGH707321220
[1] => SOME
[2] => WORDS
[3] => HERE
)
//etc
Joining the arrays together
array_walk($array2, function($values, $key) use (&$array1) {
$array1[$key] = array_merge($array1[$key], $values);
} );
After The array Merge - print_r($array1)
[1] => Array
(
[0] => 2017-07-21 00:00:00
[1] => Foo
[2] => Bar
[3] => 32.63
[4] => 18.36
[5] => 98.46
[6] => RTGH707321222
[7] => THIS
[8] => IS
[9] => TEXT
)
[2] => Array
(
[0] => 2017-07-21 00:00:00
[1] => Foo
[2] => Bar
[3] => 29.74
[4] => 148.68
[5] => 178.42
[6] => RTGH707321220
[7] => SOME
[8] => WORDS
[9] => HERE
)
//etc
So this is working fine. However, I would like to move some of these indexes around so that they are in a different order. I have looked into array_splice() but I am not sure if this is the correct method to use.
What I want it to look like
[1] => Array
(
[0] => 2017-07-21 00:00:00
[1] => RTGH707321222
[2] => TEXT
[3] => THIS
[4] => 18.36
[5] => 98.46
[6] => Foo
[7] => 32.63
[8] => IS
[9] => Bar
)
//etc
As you can see, all the information is still the same. The values have just been moved to different indexes. How can I sort the array so that it looks like the above. Can anyone point me in the right direction? Thanks.
This is a simpler method using array_replace() and an ordering array.
No extra loop, no temporary swapping variables.
Code: (Demo)
$array1=[
1=>['2017-07-21 00:00:00','Foo','Bar',32.63,18.36,98.46],
2=>['2017-07-21 00:00:00','Foo','Bar',29.74,148.68,178.42]
];
$array2=[
1=>['RTGH707321222','THIS','IS','TEXT'],
2=>['RTGH707321220','SOME','WORDS','HERE']
];
$order=[0=>'',6=>'',9=>'',7=>'',4=>'',5=>'',1=>'',3=>'',8=>'',2=>''];
array_walk($array2, function($values, $key) use (&$array1,$order) {
$array1[$key] = array_replace($order,array_merge($array1[$key], $values));
});
var_export($array1);
we can use swap technice here like,
<?php
foreach ($arr as $key => $value) {
$swap = $value[1];
$arr[$key][1] = $value[6];
$arr[$key][6] = $swap;
$swap = $value[9];
$arr[$key][9] = $value[2];
$arr[$key][2] = $swap;
$swap = $value[7];
$arr[$key][7] = $value[3];
$arr[$key][3] = $swap;
}
print_r($arr);
?>
$arr is your array.

scandir() scan by increasing number

I want to scan a directory and add all the file-names to an array in ascending order (numeric, no letters). What appears to be happening is scandir() is sorting them by highest value of the first number and not the whole number. I need to take into account missing text files, so if 9.txt was missing, 10.txt would take its place (no empty spot in array).
Here is the code:
<?php
$array=array();
$int = 1;
$holder=scandir("/postexamples/");
krsort($holder);
foreach($holder as $x)
{
if(!is_dir($x)){
$array[$int]=$x;
$int++;
}
}
echo PHP_EOL . PHP_EOL . "Final array: " , PHP_EOL;
print_r($array);
?>
Which outputs the array:
Array ( [1] => 9.txt [2] => 8.txt [3] => 7.txt [4] => 6.txt [5] => 5.txt [6] => 4.txt [7] => 3.txt [8] => 20.txt [9] => 2.txt [10] => 19.txt [11] => 18.txt [12] => 17.txt [13] => 16.txt [14] => 15.txt [15] => 14.txt [16] => 13.txt [17] => 12.txt [18] => 11.txt [19] => 10.txt [20] => 1.txt )
Is there a better (and preferably working) way to do this? I need it to be like [1] => 1.txt [2] => 2.txt
EDIT:
I need the array to appear like this:
Array ( [1] => 1.txt [2] => 2.txt [3] => 3.txt [4] => 4.txt [5] => 5.txt [6] => 6.txt [7] => 7.txt [8] => 8.txt [9] => 9.txt [10] => 10.txt [11] => 11.txt [12] => 12.txt [13] => 13.txt [14] => 14.txt [15] => 15.txt [16] => 16.txt [17] => 17.txt [18] => 18.txt [19] => 19.txt [20] => 20.txt )
And if one file (for example, 17.txt) was missing, it would look like this:
Array ( [1] => 1.txt [2] => 2.txt [3] => 3.txt [4] => 4.txt [5] => 5.txt [6] => 6.txt [7] => 7.txt [8] => 8.txt [9] => 9.txt [10] => 10.txt [11] => 11.txt [12] => 12.txt [13] => 13.txt [14] => 14.txt [15] => 15.txt [16] => 16.txt [17] => 18.txt [18] => 19.txt [19] => 20.txt )
You need to do a natural sort to get the files in the correct order (20.txt, 10.txt, 2.txt, 1.txt). The function for doing this is natsort.
$sortPath = 'postexamples/';
$files = array();
foreach (scandir($sortPath) as $file) {
if (is_file("$sortPath/$file")) {
$files[] = $file;
}
}
echo PHP_EOL . PHP_EOL . "Final array: " , PHP_EOL;
natsort($files);
$files = array_values($files); // re-key array
print_r($files);
Result
Final array:
Array
(
[0] => 1.txt
[1] => 2.txt
[2] => 4.txt
[3] => 10.txt
[4] => 20.txt
)
Id do it like this.
$files = array_diff(scandir("/postexamples/"), array('.', '..' ));
$array = array();
foreach($files as $file){
if(!is_dir($file)){
$array[]=$file;
}
}
sort($array, SORT_NUMERIC);
You may have to use usort, if it doesn't do the numbers right. Also if you are on php >= 5.4 you may be able to use,
scandir("/postexamples/", SCANDIR_SORT_ASCENDING );
But I haven't tried it. Using sort with numeric flag ( don't forget it's just an array like any other )
$a = Array ( '9.txt', '8.txt', '7.txt', '6.txt', '10.txt', '1.txt');
echo "<pre>";
var_export($a);
echo "<br>";
sort($a, SORT_NUMERIC);
var_export($a);
Result
array (
0 => '9.txt',
1 => '8.txt',
2 => '7.txt',
3 => '6.txt',
4 => '10.txt',
5 => '1.txt',
)
array (
0 => '1.txt',
1 => '6.txt',
2 => '7.txt',
3 => '8.txt',
4 => '9.txt',
5 => '10.txt',
)
So essentially sort($a, SORT_NUMERIC);
Try this ,i hope this will help you:
$ar=array();
$g=scandir("/postexamples/");
krsort($g)
foreach($g as $x)
{
if(is_dir($x))$ar[$x]=scandir($x);
else $ar[]=$x;
}
print_r(sort($ar));

Replace value in multi dimension array

I have array format like:
Array
(
[Australia] => Array
(
[0] => [1990,0.01],
[1] => [1991,0.02],
[2] => [1992,0.02],
[3] => [1993,0.02],
[4] => [1994,0.02],
[5] => [1995,0.02],
[6] => [1996,0.02],
[7] => [1997,0.02],
[8] => [1998,0.02],
[9] => [1999,0.02],
[10] => [2000,0.02],
[11] => [2001,0.02],
[12] => [2002,0.02],
[13] => [2003,0.02],
[14] => [2004,0.02],
[15] => [2005,0.02],
[16] => [2006,0.02],
[17] => [2007,0.02],
[18] => [2008,0.02],
[19] => [2009,empty],
[20] => [2010,empty],
[21] => [2011,empty],
[22] => [2012,empty],
[23] => [2013,empty],
[24] => [2014,empty],
[25] => [2015,empty]
)
[Pakistan] => Array
(
[0] => [1990,0.00],
[1] => [1991,0.00],
[2] => [1992,0.00],
[3] => [1993,0.00],
[4] => [1994,0.00],
[5] => [1995,0.00],
[6] => [1996,0.00],
[7] => [1997,0.00],
[8] => [1998,0.00],
[9] => [1999,0.00],
[10] => [2000,0.00],
[11] => [2001,0.00],
[12] => [2002,0.00],
[13] => [2003,0.00],
[14] => [2004,0.01],
[15] => [2005,0.01],
[16] => [2006,0.00],
[17] => [2007,0.00],
[18] => [2008,0.00],
[19] => [2009,empty],
[20] => [2010,empty],
[21] => [2011,empty],
[22] => [2012,empty],
[23] => [2013,empty],
[24] => [2014,empty],
[25] => [2015,empty]
)
)
and i want to replace 'empty' with 0 without change the array structure and elements position. I stuck how to do..
You can use array_walk_recursive function:
function replace_empty(&$item, $key) {
$item = str_replace('empty', '0', $item);
}
array_walk_recursive($your_array, 'replace_empty');
You could use the array_walk_recursive function, with a callback function that would replace empty by 0.
For example, considering your array is declared this way :
$myArray[0] = array(23, empty, 43, 12);
$myArray[1] = array(empty, empty, 53, 19);
Note : I supposed you made a typo, and your arrays are not containing only a string, but several sub-elements.
You could use this kind of code :
array_walk_recursive($myArray, 'replacer');
var_dump($myArray);
With the following callback functon :
function replacer(& $item, $key) {
if ($item === empty) {
$item = 0;
}
}
Note that :
the first parameter is passed by reference !
which means modifying it will modify the corresponding value in your array
I'm using the === operator for the comparison
And you'd get the following output :
array(
0 =>
array
0 => int 23
1 => int 0
2 => int 43
3 => int 12
1 =>
array
0 => int 0
1 => int 0
2 => int 53
3 => int 19)
I would foreach in both indices (not tested):
foreach($array as $country){
foreach($country as &$field){
if($field[1] == 'empty'){
$field[1] = 0;
}
}
}
(I assume empty is a string)
EDIT:
If this [1990,0.00] is not an array but a string, you could use str_replace instead
foreach($array as $country){
foreach($country as &$field){
$field = str_replace('empty', '0.00', $field);
}
}
}

get specific values of array not showing

This is what my array looks like :
Array (
[0] => SimpleXMLElement Object (
[key] => Array (
[0] => Track ID
[1] => Name
[2] => Artist
[3] => Album Artist
[4] => Composer
[5] => Album
[6] => Genre
[7] => Kind
[8] => Size
[9] => Total Time
[10] => Disc Number
[11] => Disc Count
[12] => Track Number
[13] => Year
[14] => Date Modified
[15] => Date Added
[16] => Bit Rate
[17] => Sample Rate
[18] => Play Count
[19] => Play Date
[20] => Play Date UTC
[21] => Artwork Count
[22] => Persistent ID
[23] => Track Type
[24] => Location
[25] => File Folder Count
[26] => Library Folder Count )
[integer] => Array (
[0] => 2056
[1] => 3732918
[2] => 230661
[3] => 1
[4] => 1
[5] => 1
[6] => 1993
[7] => 128
[8] => 44100
[9] => 3
[10] => 3439412487
[11] => 1
[12] => 5
[13] => 1 )
[string] => Array (
[0] => Eye of the Tiger
[1] => Survivor
[2] => Survivor
[3] => Frankie Sullivan/Jim Peterik
[4] => Greatest Hits
[5] => Rock
[6] => MPEG audio file
[7] => 772F0F53F195E705
[8] => File
[9] => file://localhost/Users/cameron/Music/iTunes/iTunes%20Media/Music/Survivor/Greatest%20Hits/01%20Eye%20of%20the%20Tiger.mp3 )
[date] => Array (
[0] => 2012-08-27T17:01:00Z
[1] => 2012-08-27T17:01:03Z
[2] => 2012-12-27T07:21:27Z ) )
that's 1 result, there is about 50 of them repeated.
I am trying to select the artist value in this case : Frankie Sullivan/Jim Peterik
please note: there is about 50 other results that come after this first one, so I would like to do a foreach to display all results.
any suggestions? I am stuck.this is the code I used to get these results:
$xml = simplexml_load_file('Library.xml');
$xmlx = $xml->dict->dict->dict->key;
$artist = $xmlx->xpath("//dict[key='Artist']");
echo "<pre>" . print_r($artist, true) . "</pre>";
It seems that you have an array of SimpleXMLElement,
so you can iterate over your array and use the SimpleXMLElement facilities.
Try:
foreach($yourArray as $simpleXmlElement)
{
// Retrieve the name
echo $simpleXmlElement->string[3];
}
Take a look at the documentation for more question: SimpleXMLElement
For your specific problem, assuming the key and string are synchronized, you can try:
// Loop on your array of SimpleXMLElement
foreach($yourArray as $simpleXmlElement)
{
// Initialize the position and found value
$position = 0;
$found = false;
// Loop on the sub array 'key' and search the 'Artist Album' position
foreach($simpleXmlElement->key as $index => $value)
{
if ($value == "Album Artist")
{
$found = true;
break;
}
// Not found, increment position
$position++;
}
// Retrieve the name if found the artist album key
if ($found)
echo $simpleXmlElement->string[$position];
}
As
[3] => Album Artist
will give the position 3
Then, when retrieving the string value, it will return Frankie Sullivan/Jim Peterik

Categories