PHP array does not sort at all - php

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder

Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

Related

Replace array value with more than one values

I have an array like this,
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
I want to find any value with an ">" and replace it with a range().
The result I want is,
array(
1,2,3,4,5,6,7,8,9,10,11,12, '13.1', '13.2', 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
);
My understanding:
if any element of $array has '>' in it,
$separate = explode(">", $that_element);
$range_array = range($separate[0], $separate[1]); //makes an array of 4 to 12.
Now somehow replace '4>12' of with $range_array and get a result like above example.
May be I can find which element has '>' in it using foreach() and rebuild $array again using array_push() and multi level foreach. Looking for a more elegant solution.
You can even do it in a one-liner like this:
$array = array(1,2,3,'4>12','13.1','13.2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,#range(...array_slice(explode(">","$c>$c"),0,2)));},
[]
));
I avoid any if clause by using range() on the array_slice() array I get from exploding "$c>$c" (this will always at least give me a two-element array).
You can find a little demo here: https://rextester.com/DXPTD44420
Edit:
OK, if the array can also contain non-numeric values the strategy needs to be modified: Now I will check for the existence of the separator sign > and will then either merge some cells created by a range() call or simply put the non-numeric element into an array and merge that with the original array:
$array = array(1,2,3,'4>12','13.1','64+2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,strpos($c,'>')>0?range(...explode(">",$c)):[$c]);},
[]
));
See the updated demo here: https://rextester.com/BWBYF59990
It's easy to create an empty array and fill it while loop a source
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$res = [];
foreach($array as $x) {
$separate = explode(">", $x);
if(count($separate) !== 2) {
// No char '<' in the string or more than 1
$res[] = $x;
}
else {
$res = array_merge($res, range($separate[0], $separate[1]));
}
}
print_r($res);
range function will help you with this:
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$newArray = [];
foreach ($array as $item) {
if (strpos($item, '>') !== false) {
$newArray = array_merge($newArray, range(...explode('>', $item)));
} else {
$newArray[] = $item;
}
}
print_r($newArray);

How to print PHP array values without square brackets and symbols?

I want to print an array without printing the square brackets and the word "Array", for example if I do
print_r($Array);
I will get this:
Array ( [0] => Example0 [1] => Example1)
How can I get this?
Example0
Example1
Any of these ways should work just fine.
// First way
print_r(implode("<br>", $your_array));
// Second way
for ($i = 0; $i < count($your_array); $i++) {
print_r($your_array[$i]);
echo "<br>";
}
// Third way
foreach ($your_array as $value) {
print_r($value);
echo "<br>";
}
The first method works for one-dimensional arrays only. If you have multidimensional arrays, you need to use for loops and to check whether the current element is an array or not and recursively enter into more for loops in order to print out all the data.
You can do it in this way:
function print_array ($array) {
foreach ($array as $key => $value) {
if (is_array ($value)) {
print_array ($value);
} else {
echo ($value."<br />");
}
}
}
You could use array walk recursive
$array = ['Example0','Example1', ['Example2']];
array_walk_recursive($array,function($item,$key){echo"$item\n";});
// tip use <br> instead of \n for HTML
Outputs
Example0
Example1
Example2
See it online
array_walk_recursive — Apply a user function recursively to every member of an array
So this will seamlessly handle multi-dimensional arrays, as my example shows.
If I understood correctly, you want to print the values for each key. You can use
foreach ($Array as $value) {
print_r($value);
echo "\n";
}
This will result in
Example0
Example1
foreach($Array as $key) {
echo $key.", ";
}

Retrieve Highest Value from Array in PHP

I would post the entire code, but it is lengthly and confusing, so I'll keep it short and simple. This is complicated for myself, so any help will be greatly appreciated!
These are the values from my Array:
Light Blue1
Blue2
Blue1
Black3
Black2
Black1
The values I need to retrieve from my Array are "Light Blue1", "Blue2" and "Black3". These are the "highest values" for each color.
Something similar to what I'm looking for is array_unique, but that wouldn't work here. So something along those lines that can retrieve each color with its highest number.
Thanks!
Assuming your format is always NameNumber a regex should do the trick for separating the data. This will loop through your data in the order your provide and grab the first element that is different and put it into $vals. I am also assuming your data will always be ordered as your example shows
$data = ['Light Blue1',
'Blue2',
'Blue1',
'Black3',
'Black2',
'Black1'];
$vals = [];
$current = '';
foreach($data as $row) {
if(!preg_match('/(.*)(\d)/i', $row, $matched)) continue;
if($matched[1] != $current) {
$vals[] = $row;
$current = $matched[1];
}
}
The solution using preg_split and max functions:
$colors = ['Light Blue1', 'Blue2', 'Blue1', 'Black3', 'Black2', 'Black1'];
$unique_colors = $result = [];
foreach ($colors as $k => $v) {
$parts = preg_split("/(\d+)/", $v, 0, PREG_SPLIT_DELIM_CAPTURE);
$unique_colors[$parts[0]][] = (int) $parts[1];
}
foreach ($unique_colors as $k => $v) {
$result[] = $k . max($v);
}
print_r($result);
The output:
Array
(
[0] => Light Blue1
[1] => Blue2
[2] => Black3
)
If you pre-sort your array with "natural sorting", then you can loop through the array and unconditionally push values into the result with digitally-trimmed keys. This will effectively overwrite color entries with lesser number values and only store the the highest numbered color when the loop finishes.
Code: (Demo)
natsort($data);
$result = [];
foreach ($data as $value) {
$result[rtrim($value, '0..9')] = $value;
}
var_export(array_values($result));
Or you could parse each string and compare the number against its cached number (if encountered before): (Demo)
$result = [];
foreach ($data as $value) {
sscanf($value, '%[^0-9]%d', $color, $number);
if (!isset($result[$color]) || $result[$color]['number'] < $number) {
$result[$color] = ['value' => $value, 'number' => $number];
}
}
var_export(array_column($result, 'value'));
A related technique to find the highest value in a group

Create multiple span based on array

I have an array that looks like this:
$elm = 'a,b,c';
I need the values of the array so I use explode to get to them:
$q = explode(",",$elm);
I then would like to echo every single item into a span, so I make an array:
$arr = array();
foreach($html->find($q[0]) as $a) {
$arr[] = $a->outertext;
}
$arr2 = array();
foreach($html->find($q[1]) as $b) {
$arr2[] = $b->outertext;
}
$arr3 = array();
foreach($html->find($q[2]) as $c) {
$arr3[] = $c->outertext;
}
And then finally I output like this:
echo "<ul>";
for($i=0; $i<sizeof($arr + $arr2 + $arr3); $i++)
{
echo "<li>";
echo "<span>".$arr[$i]."</span>";
echo "<span>".$arr2[$i]."</span>";
echo "<span>".$arr3[$i]."</span>";
echo "</li>";
}
echo "</ul>";
The problem is that I have to write all the items ($q[0] + $q[1] + $q[2]) and the corresponding span (<span>".$arr[$i]."</span>) This is a problem because in reality I don't know what and how long the first array ($elm) is. Therefore I don't want to 'physically' write down all the span elements but rather create them on the fly depending on the array $elm. I tried many things but I can't figure it out.
The basic issue here is that you don't know how many elements $elm will contain. foreach is the best choice here, as it doesn't require the length of the array to loop through it.
Use a nested foreach loop to store all the outertexts in an array:
foreach (explode(",", $elm) as $elem) {
foreach ($html->find($elem) as $a) {
$arr[$elem][] = $a->outertext;
}
}
$arr[$elem][] is the important bit here. On each iteration of the outer loop, the value of $elem will be a, b and c. On each iteration of the inner loop, it will create a new index in the array: $arr['a'], $arr['b'] and $arr['c'] and add the outertext values to the respective index.
Once you've stored all the required values in the array, it's only a matter of looping through it. Since we have a multi-dimensional array here, you will need to use a nested loop again:
echo "<ul>";
foreach ($arr as $sub) {
echo "<li>";
foreach ($sub as $span) {
echo "<span>".$span."</span>";
}
echo "</li>";
}
echo "</ul>";

php, how to compare the 2 arrays from different queries?

i have 2 queries, and i get back some data by doing a whyle loop.
from the first query if i do print_r($final_key);i get:
hey1
hey2
hey3
from the second one, if i do print_r($final_key2); i get:
hey1 test
hey2 test1
hey3
what i am trying to do is to compare the 2 arrays and check for words that match
and i can't do it directly from the database
any ideas?
thanks
edit:
here is my query 1:
while ($keywords = mysql_fetch_array($keys1, MYSQL_ASSOC)){
foreach ($keywords as $key) {
$plus = '+';
$pos = strripos($key, $plus);
if ($pos === false) { } else {
$clean_plus = preg_replace("/[\+]/", '', $key);
$final_key = str_replace("'", "", $clean_plus);
print_r($final_key);
echo '<br>';
}
}
}
and the second one:
<?php
while ($keywords = mysql_fetch_array($keys)){
if($keywords['kword'] != ''){
echo $keywords['kword'];
} } ?>
i am tryingt o match $final_key against $keywords['kword'];
Use array_intersect:
array_intersect($array1, $array2, ...);
from the array_intersect documentation:
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
Use array_intersect which returns an array containing values in both arrays.
If you want the keys to match, use array_intersect_assoc.
Loop over one array, and on each iteration, loop the other.
<?php
foreach($array as $item){
foreach($array2 as $item2){
if($item == $item2){
$array3[] = $item;
}
}
}
?>
This will create an array of matches, which you can then do with as you will.

Categories