I have a php array as follows,
<?php
$arr = array('op'=>'pqr', 'ab'=>'xyz', 'mn'=>'abcd');
?>
How to set xyz value as first element with minimum loop,if the value exist.
Expected Result
<?php
$arr = array('ab'=>'xyz', 'op'=>'pqr','mn'=>'abcd');
?>
$ab = $array['ab'];
unset($array['ab']);
$array = array('ab' => $ab) + $array;
If the key itself is unknown, find it first:
$key = array_search('xyz', $array);
$tmp = $array[$key];
unset($array[$key]);
$array = array($key => $tmp) + $array;
Or go with a sort:
uasort($array, function ($a, $b) {
if ($a == 'xyz') return -1;
if ($b == 'xyz') return 1;
return 0;
});
<?php
$arr = array('op'=>'pqr', 'ab'=>'xyz', 'mn'=>'abcd');
ksort($arr);
echo '<pre>';
print_r($arr);
Related
Let's say I Have two arrays.
$arr1 = ['A','B','C','D'];
$arr2 = ['C','D'];
now compare two arrays.if there is no match for value of $arr1 in $arr2 then index is left empty.
for the above arrays output should be:
$arr3 = ['','','C','D']
I tried array_search() function.But couldn't achieve desired output.
Any possible solutions?
You can use foreach with in_array and array_push like:
$arr1 = ['A','B','C','D'];
$arr2 = ['C','D'];
$arr3 = [];
foreach($arr1 as $value){
$arr3[] = (in_array($value, $arr2)) ? $value : '';
}
print_r($arr3);
/*
Result
Array
(
[0] =>
[1] =>
[2] => C
[3] => D
) */
Foreach the first array then test with in_array if exist, if true push into array 3 else push empty value
You can use the following function. In the following code, the function search_in_array return true and false based on the searching within the 2nd array. So you can push the empty or searched value in final array.
<?php
$arr1 = array('A','B','C','D');
$arr2 = array('C','D');
$arr3 = array();
function search_in_array ($value, $array)
{
for ($i=0; $i<count($array); $i++)
{
if ($value == $array[$i])
{
return true;
}
}
return false;
}
for ($i=0; $i<count($arr1); $i++)
{
$value = $arr1[$i];
$result = search_in_array ($value, $arr2);
if ($result)
{
array_push ($arr3, $value);
}
else
{
array_push ($arr3, '');
}
}
print_array($arr3);
?>
I have 2 arrays as follows:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
Now I want to make these two arrays to one array with following value:
$newArray = array('one.jpg', 'five.jpg', 'three.jpg');
How can I do this using PHP?
Use array_filter to remove the empty values.
Use array_replace to replace the values from the first array with the remaining values of the 2nd array.
$arr1=array_filter($arr1);
var_dump(array_replace($arr,$arr1));
Assuming you want to overwrite entries in the first array only with truthy values from the second:
$newArray = array_map(function ($a, $b) { return $b ?: $a; }, $arr, $arr1);
You can iterate through array and check value for second array :
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray =array();
foreach ($arr as $key => $value) {
if(isset($arr1[$key]) && $arr1[$key] != "")
$newArray[$key] = $arr1[$key];
else
$newArray[$key] = $value;
}
var_dump($newArray);
Simple solution using a for loop, not sure whether there is a more elegant one:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray = array();
$size = count($arr);
for($i = 0; $i < $size; ++$i) {
if(!empty($arr1[$i])){
$newArray[$i] = $arr1[$i];
} else {
$newArray[$i] = $arr[$i];
}
}
I'm trying to sort an array numerically but the integers are found in the middle of a value, not on the first character. Here is what my array looks like (using dummy values):
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
sort($array,1);
Output after foreach:
A25
A30
A40
AB25
AB30
AB40
B25
B30
B40
Expected output:
A25
AB25
B25
A30
AB30
B30
A40
AB40
B40
What would be the best sorting method for this? Really appreciate it, thanks!
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
usort(
$array,
function($a, $b) {
list($achar,$anum) = sscanf($a, '%[A-Z]%d');
list($bchar,$bnum) = sscanf($b, '%[A-Z]%d');
if ($anum > $bnum) {
return 1;
} elseif (($anum == $bnum) && ($achar > $bchar)) {
return 1;
}
return -1;
}
);
var_dump($array);
Have created a custom function depending on your requirement, please see below code
<?php
$array = array('A30','A25','ZZZ','A40','Rohan','B25','B30','Sakhale','B40','AB25','AB30','AB40');
$array = sortArrayByNumber($array);
var_dump($array);
/**
* #name sortArrayByNumber
* #abstract sort the entire array irrespective of the string, but the numbers into it
* also we append the elements not having any number at the end
* #author Rohan Sakhale
*/
function sortArrayByNumber($arr){
$sortedArr = array();
$tempArray = array();
$stringOnlyArray = array();
foreach($arr as $v){
$num = getNumberFromString($v);
/**
* If no number found, append it into stringOnlyArray
*/
if($num == ''){
$stringOnlyArray[] = $v;
continue;
}
if(!isset($tempArray[$num])){
$tempArray[$num] = array();
}
$tempArray[$num][] = $v;
}
$tempArrayKeys = array_keys($tempArray);
sort($tempArrayKeys);
foreach($tempArrayKeys as $key){
sort($tempArray[$key]);
$sortedArr = array_merge($sortedArr, $tempArray[$key]);
}
if(count($stringOnlyArray) > 0){
sort($stringOnlyArray);
$sortedArr = array_merge($sortedArr, $stringOnlyArray);
}
return $sortedArr;
}
/**
* #str - String param which tend to have number
*/
function getNumberFromString($str){
$matches = null;
preg_match_all('!\d+!', $str, $matches);
if(!is_null($matches) and is_array($matches)){
if(isset($matches[0][0])){
return $matches[0][0];
}
}
return '';
}
?>
Here sort by number method is trying to firstly identify the number's in your string and maintain a separate array of it based on the keys, later we sort in ascending order every key's of number and then we finally merge it into sorted array
You can use user defined function with usort to achieve it
<?php
function mySort($a,$b) {
$numA = '';
$strA = '';
$numB = '';
$strB = '';
for($i=0;$i<strlen($a); $i++) {
if(is_numeric($a[$i])) {
$numA .= (string)$a[$i];
}
else {
$strA .= $a[$i];
}
}
for($i=0;$i<strlen($b); $i++) {
if(is_numeric($b[$i])) {
$numB .= (string)$b[$i];
}
else {
$strB .= $b[$i];
}
}
$numA = (int)$numA;
$numB = (int)$numB;
if($numA>$numB) {
return true;
}
elseif($numA<$numB) {
return false;
}
else {
if(strcmp($strA,$strB)>0) {
return true;
}
else {
return false;
}
}
}
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
var_dump($array);
usort($array,'mySort');
var_dump($array);
?>
Here's a stable sort, the result is: "A25" "B25" "AB25" "A30" "B30" "AB30" "A40" "B40" "AB40" .
function getNum($str)
{
preg_match ( '/(\d+)$/', $str, $match );
return intval ( $match [1] );
}
function stableSort($arr)
{
$newArr = array ();
foreach ( $arr as $idx => $ele )
{
$newArr [] = array (
'idx' => $idx,
'val' => $ele
);
}
usort ( $newArr,
function ($a, $b)
{
$d = getNum ( $a ['val'] ) - getNum ( $b ['val'] );
return $d ? $d : $a ['idx'] - $b ['idx'];
} );
$sortArr = array ();
foreach ( $newArr as $ele )
{
$sortArr [] = $ele ['val'];
}
return $sortArr;
}
var_dump ( stableSort ( $array ) );
U can use various kinds of ways to sort arrays in PHP. PHP has some good ways build in to do sorting on arrays. In this case I agree with Mark Baker, however I would recommend a preg_replace to get the numeric value of your strings.
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
function cmp($a, $b)
{
$v1 = preg_replace("/[^0-9]/", "", $a);
$v2 = preg_replace("/[^0-9]/", "", $b);
if ($v1 == $v2) {
return 0;
}
return ($v1 < $v2) ? -1 : 1;
}
usort($array, "cmp");
var_dump($array);
Look into the PHP information about sorting arrays, php.net/usort and various others.
Good day.
I would be like get 3 keys from $arr where value $arN[0] will be more than other...
Code:
$ar1=array(201,281);
$ar2=array(1252760,1359724);
$ar3=array(452760,34349724);
$ar4=array(1260,134344);
$ar5=array(232750,1359724);
$ar6=array(60,1439724);
$arr[]=array(6299927 => $ar1);
$arr[]=array(1252760 => $ar2);
$arr[]=array(3432444 => $ar3);
$arr[]=array(3435543 => $ar4);
$arr[]=array(7645466 => $ar5);
$arr[]=array(4574534 => $ar6);
Next function sorting array $a descending:
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? 1 : -1;
}
$a = array(3, 2, 5, 6, 1);
usort($, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
outpoot: 0:6 1:5 2:4 3:2 4:1
But how change this function for my example(for my big array)?
Tell me please how make this?
How write right?
Very confusing but I think you are looking for something like this. It will give you the index of the array whose first item is greater than the first item in the next array.
foreach($arr as $key => $array) {
if($array[0] > $arr[$key+1][0]) {
echo $key;
}
}
$dates = array();
foreach ($arr as $key => $row) {
$subkeys = array_keys($row); // Elements are one-element associative arrays
$dates[$key] = $row[$subkeys[0]][0]; // Get the element, then get its [0] sub-element
}
array_multisort($dates, SORT_DESC, $arr);
print_r($arr);
$ans_array= array();
// for shuffle array without repeat
for($q=0;$q<count($arr);$q++)
{
$n = rand(0,count($arr));
if($ans_array[$n] == NULL || $ans_array[$n] == '')
{
$ans_array[$n] = $arr[$q];
}
else
{ if($q==0) $q=0;
else $q = $q-1;
}
}
If i have two array as following:
$array1 = array(array('id'=>11,'name'=>'Name1'),array('id'=>22,'name'=>'Name2'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'),array('id'=>55,'name'=>'Name5'));
$array2 = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'));
My expect result, the array2 should be always at the beginning :
$newarray = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'), array('id'=>11,'name'=>'Name1'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'));
My current solution is using two for loops:
foreach($array2 as $Key2 => $Value2) {
foreach($array1 as $Key1 => $Value1){
if($Value1['id'] != $Value2['id']) {
//push array
}
}
}
Edit:
The result "$newarray" should not include the duplicate ids from array1.
But i am looking for a faster and simpler solution.
SOLUTION:
$a1 = array();
foreach ($array1 as $v) $a1[$v['uuid']] = $v;
$a2 = array();
foreach ($array2 as $v) $a2[$v['uuid']] = $v;
$filtered = array_values(array_diff_key($a1, $a2));
//print_r($filtered);
$newarray = array_merge($array2, $filtered);
Thank you guys!!!!
Thanks.
Regards Jack
you want $new_array = array_merge($array2, $array1); puts the second array onto the end of the first one
You can use array_merge() function for that, like this:
$newarray = array_merge($array2, $array1);
I am not sure about your requirement but to sort multi-dimensional array on some specific key
You need to use usort function
Try the code below:
$cmp = function ($a, $b){
$a_val = $a['id'];
$b_val = $b['id'];
if ( $a_val == $b_val) {
return 0;
}
return ($a_val < $b_val) ? -1 : 1;
};
usort($array2,$cmp);
$array2 will be sorted by 'id'