How do I sort the following data in the order I want it?
The array:
array(4)
{
[21]=> string(7) "2-2.pdf"
[22]=> string(7) "2-3.pdf"
[23]=> string(7) "2-4.pdf"
[24]=> string(5) "2.pdf"
}
I want this sort:
2.pdf
2-2.pdf
2-3.pdf
2-4.pdf
Yes you could use usort in this case:
$array = [21=> "2-2.pdf", 22=> "2-3.pdf", 23=> "2-4.pdf",24=> "2.pdf", ];
usort($array, function($a, $b){
$a = str_replace('-', '', $a);
$b = str_replace('-', '', $b);
return $a - $b;
});
You can do like this:
<?php
$check_array = array('2-2.pdf','2.pdf','2-3.pdf','2-4.pdf');
function cmp($a, $b)
{
$a = preg_replace('/-/','',$a);
$b = preg_replace('/-/','',$b);
return strcmp($a, $b);
}
usort($check_array, "cmp");
echo "<pre/>"; print_r($check_array);
?>
And the result is:
<?php Array ( [0] => 2.pdf [1] => 2-2.pdf [2] => 2-3.pdf [3] => 2-4.pdf ) ?>
Related
I have an array that is like this:
array(6) { [0]=> string(116) "A" [1]=> string(112) "C" [2]=> string(110) "B" [3]=> string(115) "F" [4]=> string(113) "D" [5]=> string(112) "E" }
and which letter represents an Hyperlink, so each letter is:
Letter
I want to sort this array so I have it sorted by its letter/innerHTML
I want to sort this before echoing.
Any help will be appreciated.
Thank you
You can split the links and create new associative array using letter as key and full link as value. Try below code.
$links=['D','B','C','A'];
$new_links=[];
foreach($links as $link){
$array_1= explode(">",$link);
$array_2 = explode("<",$array_1[1]);
$new_links[$array_2[0]]=$link;
}
ksort($new_links);
You can usort with a callback that compares just the link text.
$link = '/.+>(.+)<.+/';
usort($array, function($a, $b) use ($link) {
return preg_replace($link, '\1', $a) <=> preg_replace($link, '\1', $b);
// If you're on PHP 5 without the <=> operator, you can use strcmp instead
// return strcmp(preg_replace($link, '\1', $a), preg_replace($link, '\1', $b));
});
I'm not a regex expert, so there's probably a better way to write the pattern, but the general idea is the same regardless. It's common knowledge that it's not a good idea to parse arbitrary HTML with regex, but for something like an array of <a> tags it seems pretty har̴ml҉es͝s.
I would suggest using strip_tags() and sorting the result although if you want to preserve multiple link instances you need to use a multidimensional array and sort that:
$unsortedArray = [
'Orange',
'Banana',
'Apple',
'pineapple',
'Banana',
'Apple 2',
];
$sortedArray = [];
function sortLinks($links) {
$splitArray = [];
$sortedArray = [];
foreach($links as $link) {
$label = strip_tags($link);
$splitArray[] = ['link' => $link, 'label' => $label];
}
usort($splitArray, function ($a, $b) {
return $a['label'] <=> $b['label'];
});
foreach ($splitArray as $item) {
$sortedArray[] = $item['link'];
}
return $sortedArray;
}
$sorted = sortLinks($unsortedArray);
echo '<pre>' . print_r($sorted, 1) . '</pre>';
The output should be:
Array
(
[0] => Apple
[1] => Apple 2
[2] => Banana
[3] => Banana
[4] => Orange
[5] => pineapple
)
I need to merge multiple arrays into one where a specific key & its value are same. Here is the Sample_Array1
array(n) {
[0]=> array {
["a"]=> "m1"
["b"]=> "x2"
}
[1]=> array {
["a"]=> "n1"
["b"]=> "y2"
} ....
Sample_Array2 with one common key & other different ones.
array(n) {
[0]=> array {
["b"]=> "x2"
["c"]=> "p1"
}
[1]=> array {
["b"]=> "x2"
["d"]=> "q1"
}
[2]=> array {
["b"]=> "y2"
["e"]=> "r1"
} ....
Need to merge / append Sample_Array2 to Sample_Array1 where key-"b" & its value are same. The expected output:
array(n) {
[0]=>
array(2) {
["a"]=> "m1"
["b"]=> "x2"
["c"]=> "p1"
["d"]=> "q1"
}
[1]=>
array(2) {
["a"]=> "n1"
["b"]=> "y2"
["e"]=> "r1"
} ....
I have tried so many similar questions but couldn't find the exact result.
PHP merge arrays with a condition The answer given on this link is not solving the purpose, its making different array for each new key, while I need to append the new keys in one array.
This should work, assuming you have the "b" index in all sub arrays.
$array1 = array();
$array1[] = array("a" => "m1", "b" => "x2", "c" => null);
$array1[] = array("a" => "n1", "b" => "y2");
$array2 = array();
$array2[] = array("b" => "x2", "c" => "p1");
$array2[] = array("a" => null, "b" => "x2", "d" => "q1");
$array2[] = array("b" => "y2", "e" => "r1");
function merge_on_key($array1, $array2, $key) {
$result_array = array();
foreach($array1 as $key1 => $sub_array1) {
$merged_array = array();
$sub_array1 = array_filter($sub_array1);
foreach($array2 as $key2 => $sub_array2) {
$sub_array2 = array_filter($sub_array2);
if($sub_array1[$key] == $sub_array2[$key]) {
$merged_array = array_merge($sub_array1, $sub_array2, $merged_array);
unset($array2[$key2]);
}
}
if (!empty($merged_array)) {
$result_array[] = $merged_array;
}
}
return array_merge($result_array, $array2);
}
$final_array = merge_on_key($array1, $array2, "b");
print_r($final_array);
In case you have to match the "b" index within the $array1 itself too, then simply use it twice:
$array1 = merge_on_key($array1, $array1, "b");
$final_array = merge_on_key($array1, $array2, "b");
i really have no idea what you want to achieve here - but based on your description the following code works
$arrA = [
0 =>
[
'a' => 'm1',
'b' => 'x2'
],
1 =>
[
'a' => 'n1',
'b' => 'y2'
]
];
$arrB = [
0 =>
[
'b' => 'x2',
'c' => 'p1',
],
1 =>
[
'b' => 'x2',
'd' => 'q1',
],
2 =>
[
'b' => 'y2',
'e' => 'r1',
],
];
foreach($arrB AS $arrData)
{
foreach($arrData AS $key => $val)
{
if ((isset($arrData['a']) && $arrData['a'] == $arrA[0]['a']) || (isset($arrData['b']) && $arrData['b'] == $arrA[0]['b']))
{
$arrA[0][$key] = $val;
}
elseif ((isset($arrData['b']) && $arrData['b'] == $arrA[1]['a']) || (isset($arrData['b']) && $arrData['b'] == $arrA[1]['b']))
{
$arrA[1][$key] = $val;
}
}
}
print_r($arrA);
Created the arrays similar to yours. $new_array is the resultant array that you are looking for.
$a=array();
$a[0]=array('a'=>'m1', 'b'=>'x2');
$a[1]=array('a'=>'n1', 'b'=>'y2');
$b=array();
$b[0]=array('b'=>'x2', 'c'=>'p1');
$b[1]=array('b'=>'x2', 'd'=>'q1');
$b[2]=array('b'=>'y2', 'e'=>'r1');
foreach($a as $row){
//echo '<pre>'; print_r($row);
foreach($b as $c=>$row1){
//echo '<pre>'; print_r($row1);echo $c;die;
if($row['b']==$row1['b']){
$new_array[]=array_merge($row, $row1);
}
}
}echo '<pre>'; print_r($new_array);
// Gather all values of b from both arrays
$all_b = array_unique(array_merge(array_column($arr1, 'b'), array_column($arr2, 'b')));
$res = [];
// For each b value
foreach($all_b as $b) {
$temp = [];
// Scan the arrays for items with the same b value
foreach($arr1 as $a1) {
if ($a1['b'] == $b) $temp = array_merge($temp, $a1);
}
foreach($arr2 as $a2) {
if ($a2['b'] == $b) $temp = array_merge($temp, $a2);
}
// Save them to new array
$res[] = $temp;
}
print_r($res);
demo on eval
I want to make some encryption and write numbers
I used:
$a = [100,101,102,103,104,105]
function decrition (array $a){
return preg_replace('/101/','a',$a);
}
And it's returns me all letters "a" for each 101 in array.
How can I change next? 101 to "b", 102 to "c" etc.
return preg_replace('[101|102|103|104|105]','a',$a);
this method replace all this numbers to letter "a"
return preg_replace('[101|102|103|104|105','a|b|c|d|e',$a);
unfortunately it's not working
Why do you try to treat it as a string?
<?php
$a = [ 101, 102, 103 ];
$replace_array = array(101 => "a", 102 => "b");
$b = array_map(function($val) use ($replace_array) {
return (isset($replace_array[$val]) ? $replace_array[$val] : $val);
}, $a);
var_dump($a, $b);
Gives the following output:
array(3) {
[0]=>
int(101)
[1]=>
int(102)
[2]=>
int(103)
}
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
int(103)
}
Maybe you are looking for something like this?
$test = str_replace($a, array('a','b','c','d','e','f'), $a);
print_r($test);
This solution works
return str_replace(['101', '102', '103', '104', '105'], ['a', 'b', 'c', 'd', 'e'], $a);
I have an array that looks like this:
a 12 34
b 12345
c 123456
So the array looks like
$array[0] = "a 12 34"
$array[1] = "b 12345"
$array[2] = "c 123456"
I am trying to create an associative array such that
[a] => 12 34
[b] => 12345
[c] => 123456
Can I possibly split the array into two, one for containing "a, b, c" and another for their contents and use the array_combine()? Or are there any other ways?
You can do that within a loop like the snippet below demonstrates. Quick-Test here:
$array = array("a 12 34", "b 12345", "c 123456");
$array2 = array();
foreach($array as $data){
preg_match("#([a-z])(\s)(.*)#i", $data, $matches);
list(, $key, $space, $value) = $matches;
$array2[$key] = $value;
}
var_dump($array2);
// YIELDS::
array(3) {
["a"]=> string(5) "12 34"
["b"]=> string(5) "12345"
["c"]=> string(6) "123456"
}
Or using a Blend of array_walk() and array_combine() which can be Quick-Tested Here.
<?php
$array = array("a 12 34", "b 12345", "c 123456");
$keys = array();
array_walk($array, function(&$data, $key) use (&$keys){
$keys[] = trim(preg_replace('#(\s.*)#i', '', $data));;
$data = trim(preg_replace('#(^[a-z])#i', '', $data));
});
$array = array_combine($keys, $array);
var_dump($array);;
// YIELDS::
array(3) {
["a"]=> string(5) "12 34"
["b"]=> string(5) "12345"
["c"]=> string(6) "123456"
}
You can do it without any difficulty :) A simple loop is possible to do it.
Create new array
Lopp on each row
Split each data (explode(' ', $row, 2), strstr, substr, ...) ?
Put data on your new array $array[$key] = $value;
You could use a combination of array_map, array_column and array_combine:
$array = array_map(function ($v) { return explode(' ', $v, 2); }, $array);
$array = array_combine(array_column($array, 0), array_column($array, 1));
What I need is really simple:
I have two arrays like that:
<?php
$a1 = [1,2,3];
$a2 = [2,3,4];
I need to combine them so that the result is:
$result = [1,2,3,4];
I've tried array_merge but the result was [1,2,3,2,3,4]
You can find an answer to this here: Set Theory Union of arrays in PHP
By expanding on your current method. You can call array_unique and sort on the resulting array.
$a = [1,2,3];
$b = [2,3,4];
$result = array_merge($a, $b);
$result = array_unique($result);
sort($result);
This will result in:
array(4) {
[0] = int(1) 1
[1] = int(1) 2
[2] = int(1) 3
[3] = int(1) 4
}
function merges(/*...*/){
$args=func_get_args();
$ret=array();
foreach($args as $arg){
foreach($arg as $key=>$v)
{
$ret[$key]=$v;
}
}
return $ret;
}
untested, but i guess this would work.. will delete all duplicate keys and return the last key/value pair it found of duplicates
This might be what you are looking for
$result = $a1 + $a2 //union operation
reference
Array Operations
Example
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
Ouput
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}