associative array in sort using php - php

$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
Array
(
[0] => 5
[1] => 4
[2] => 1
[3] => 2
)
Expecting result
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
)
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
$results = [];
foreach($array as $key=>$value){
$results[$key] = arsort($value);
}
echo "<pre>";
print_r($results);
Please suggest how do we can sort associative array i did try but does not work for me please guide

As per your "expected results' it seems like you don't wish to maintain the keys. If that's the case then you can just use sort.
Something like this..
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
sort($array);
print_r($array);

Just do
sort($array);
Also check the PHP documentation if you need further customization: http://php.net/manual/en/function.sort.php

var_dump( array_reverse($array,false));
you don't need to use foreach or sort ,you can just use array_reverseinstead ,avery simple way

You don't need to iterate using foreach for sorting
Just use sort for sorting array
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
sort($array);
print_r($array);
This will not maintain array keys and if you want arrays keys to be same just replace sort with asort in above code

Related

How can I merge array's items?

I have an array like this:
$arr = array ( [0] => array("red","green"),
[1] => array("blue","yellow")
);
And this is expected result:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
See? I want to merge all items of $arr (which are also array themselves). How can I do that?
I can do a loop on it and then use array_merge() every time like this:
$res = [];
foreach ( $arr as $item ) {
$res = array_merge($res, $item);
}
It works as well. But I guess I can write it better. Any idea?
You can do trick with call_user_func_array:
$result = call_user_func_array('array_merge', $arr);
This trick is possible, because array_merge accept dynamic arguments count.
It's a style exercise, but if the structure remains the same as in your example, you can play with this:
$arr = array ( '0' => array("red","green"),
'1' => array("blue","yellow")
);
$res = explode(",",str_replace(array('[',']'),'',json_encode($arr)));
Hope this helps.
You declare array in wrong way:
$arr = array ( 0 => array("red","green"),
1 => array("blue","yellow")
);
The error reported by PHP says it clearly:
Fatal error: Illegal offset type in /in/Hhfqa on line 3
Line 3 in your example is exactly line of first array element.
Please check http://php.net/manual/en/language.types.array.php

multidimensional array to indexed array in php

i have this multidimensional array.
Array
(
[0] => Array
(
[car] => Toyota
)
[1] => Array
(
[car] => Ford
)
[2] => Array
(
[car] => Isuzu
)
[3] => Array
(
[car] => Chevrolet
)
)
i want to put them into indexed array like this..
Array = ("Toyota", "Ford", "Isuzu", "Chevrolet");
$result = array_map(function($item)
{ return $item['car']; }, $array);
Some functional approach. array_map
P.S. PHP has no indexed arrays
foreach($yourArray as $carArray)
{
$result[]=$carArray["car"];
}
And your understanding of indexed arrays is wrong. That example output you've shown contains all those values, not indexes, and since you didn't specify an index it will start from 0 and so on.
Option using array_map(), assuming your initial array is $arr
$new_arr = array_map(function($x){return $x['car'];}, $arr);
See demo
try using foreach and array_values, then save it into empty array. Hope it helps.

PHP Convert multidimensional array to match format of another

I have two arrays, one is generated by using explode() on a comma separated string and the other is generated from result_array() in Codeigniter.
The results when doing print_r are:
From explode():
Array
(
[0] => keyword
[1] => test
)
From database:
Array
(
[0] => Array
(
[name] => keyword
)
[1] => Array
(
[name] => test
)
)
I need them to match up so I can use array_diff(), what's the best way to get them to match? Is there something other than result_array() in CI to get a compatible array?
You could create a new array like this:
foreach($fromDatabase as $x)
{
$arr[] = $x['name'];
}
Now, you will have two one dim arrays and you can run array_dif.
$new_array = array();
foreach ($array1 as $line) {
$new_array[] = array('name' => $line);
}
print_r($new_array);
That should work for you.

How to reorder array in PHP?

I need to reorder an array in PHP.
The array:
Array
(
[0] => /riado/?p=1
[1] => /riado/?p=2
[2] => /riado/?p=3
[3] => /riado/?p=4
)
How to reorder to:
Array
(
[0] => /riado/?p=4
[1] => /riado/?p=3
[2] => /riado/?p=2
[3] => /riado/?p=1
)
I have searched but I can't find much clues. Can you give me some clues on how to achieve this?
$array = array_reverse($array);
Will reverse the contents of $array, no matter the sort order of the contents.
rsort($array);
Will sort the array in reverse alphabetical order.
rsort($arr);
That should do the trick
A simple rsort should produce the results you require if you want to sort the array in reverse order. (If you simply want to swap the elements from first to last, etc. you could of course use array_reverse or simply iterate over the array from last to first.)
reverse sort example:
<?php
$testArray = array('/riado/?p=1', '/riado/?p=2', '/riado/?p=3', '/riado/?p=4');
rsort($testArray);
print_r($testArray);
?>
array_reverse example:
<?php
$testArray = array('/riado/?p=1', '/riado/?p=2', '/riado/?p=3', '/riado/?p=4');
$testArray = array_reverse($testArray);
print_r($testArray);
?>

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

Categories