Sorting an array by a certain key - php

I have the following array:
Array
(
[Places] => Array
(
[public] => 0
[entities] => Array
(
...
)
)
[Issues] => Array
(
[public] => 1
[entities] => Array
(
...
)
)
[Source] => Array
(
[public] => 0
[entities] => Array
(
...
)
)
)
I would like to be able to sort by the array by the public key. I know I may have to use either ksort or usort but I am unsure on how to implement this.
Any ideas would be great thanks!

usort($array, function ($a, $b) { return $a["public"] - $b["public"]; });

Here's an interesting link: http://www.the-art-of-web.com/php/sortarray/
I would try a
usort(usort(array, function), function);
I can try a sample code upon request, but the information is already there for the taking.

take a look at this, using array_multisort :
$test = array(
'Places' => array(
'public' => 0,
'entities' => array(
)
),
'Issues' => array(
'public' => 1,
'entities' => array()
),
'Source' => array(
'public' => 0,
'entities' => array()
)
);
echo '<pre>';
print_r($test);
echo '</pre>';
array_multisort($test,SORT_ASC,$test);
echo '<pre>';
print_r($test);
echo '</pre>';

The general way to do this using array_multisort is to place your sorting value into its own array and then sort both arrays using that as the primary sorting array.
Try the following:
$test = array(
'Places' => array(
'public' => 0,
'entities' => array(
)
),
'Issues' => array(
'public' => 1,
'entities' => array()
),
'Source' => array(
'public' => 0,
'entities' => array()
)
);
echo '<pre>';
print_r($test);
echo '</pre>';
$sort = array();
foreach ($test as $k => $a) {
$sort[$k] = $a['public'];
}
// placing $sort first in array_multisort causes $test to be sorted in same order as the values in $sort
array_multisort($sort,SORT_ASC,$test);
echo '<pre>';
print_r($test);
echo '</pre>';

You could use usort with callback function.
function cmp($a, $b) {
return $a['public'] == $b['public'] ? 0 : $a['public'] > $b['public'] ? 1 : -1;
}
usort($array, "cmp");

Try this:
$code = "return (-1*strnatcmp(\$a['public'], \$b['public']));";
uasort($array, create_function('$a,$b', $code));

Related

PHP sort multidimensional array by array list priority [duplicate]

This question already has answers here:
Sorting a php array of arrays by custom order
(8 answers)
Closed 28 days ago.
I have array $data containing data about animals. I would like to sort this array by child element:
source array ($data):
Array (
[0] => (
'name' => 'Leo'
'type' => 'cat'
)
[1] => (
'name' => 'Max'
'type' => 'dog'
)
[2] => (
'name' => 'Elsa'
'type' => 'fish'
)
...
)
priority array ($priority)
$priority = [
'fish', 'dog', 'cat',
];
I would like to sort source array using priority array. I tried:
sort($data, function (int $item1, int $item2) use($priority) {
foreach($priority as $key => $value) {
if($item1 == $value)
{
return 0;
break;
}
if($item2 == $value)
{
return 1;
break;
}
}
return 0;
});
You can use usort with a custom compare function, like so:
<?php
$arr = array(
0 => array(
'name' => 'Leo',
'type' => 'cat'
),
1 => array(
'name' => 'Max',
'type' => 'dog'
),
2 => array(
'name' => 'Elsa',
'type' => 'fish'
)
);
$priority = array('fish', 'dog', 'cat');
usort($arr, function($a, $b) use($priority) {
return array_search($a['type'], $priority) <=> array_search($b['type'], $priority);
});
var_dump($arr);
How this works:
usort accepts a custom compare function, you can pass it the priority array, then use the spaceship operator to compare the value indexes in priority.
Try it out: http://sandbox.onlinephpfunctions.com/code/03fdfa61b1bd8b0b84e5f08ab11b6bc90eeaef4a

Compare element in array and loop through each php

I want to compare a value of data to a list of element which I had retrieved from php array(decoded json).
First,
This is the first array:
Array1
(
[0] => Array
(
[member_id] => 3
[member_card_num] => 2013011192330791
[member_barcode] => 2300067628912
)
[1] => Array
(
[member_id] => 4
[member_card_num] => 2328482492740000
[member_barcode] => 3545637000
)
[2] => Array
(
[member_id] => 2
[member_card_num] => 40001974318
[member_barcode] => 486126
)
[3] => Array
(
[member_id] => 1
[member_card_num] => 91001310000057698
[member_barcode] => 000057698
)
)
This is the second Array:
Array2
(
[0] => Array
(
[member_id] => 2
[member_card_num] => 40001974318
[member_barcode] => 486126
)
)
Second,
I had retrieved the (member_barcode) which I required.
Here is the code:
For Array1:
foreach ($decode1 as $d){
$merchant_barcode = $d ['member_barcode'];
echo $merchant_barcode;
}
For Array2:
foreach ($decode2 as $d2){
$user_barcode = $d2 ['member_barcode'];
echo $user_barcode;
}
Then,
I get this output():
For Array1(merchant_barcode):
2300067628912
3545637000
486126
000057698
For Array2(user_barcode):
486126
The question is, I would to check and compare whether the user_barcode in Array2(486126) is exist/match to one of the merchant_barcode in Array1.
This is my code,
but it only compare the user_barcode in Array2 to the last element(000057698) in Array1,
I want it to loop through each n check one by one. How can I do that?
public function actionCompareBarcode($user_barcode, $merchant_barcode){
if(($user_barcode) == ($merchant_barcode)){
echo "barcode exist. ";
}
else{
echo "barcode not exist";
}
}
In this case, the output I get is "barcode not exist", but it should be "barcode exist".
Anyone can help? Appreciate that. Im kinda new to php.
You could use a nested loop like:
foreach ($decode2 as $d2)
{
$user_barcode = $d2 ['member_barcode'];
foreach ($decode1 as $d)
{
$merchant_barcode = $d ['member_barcode'];
if ($merchant_barcode == $user_barcode)
{
echo "Match found!";
}
else
{
echo "No match found!";
}
}
}
<?
$a = array(
array(
'member_id' => 3,
'member_card_num' => '2013011192330791',
'member_barcode' => '2300067628912',
),
array(
'member_id' => 4,
'member_card_num' => '2328482492740000',
'member_barcode' => '3545637000',
),
array(
'member_id' => 2,
'member_card_num' => '40001974318',
'member_barcode' => '486126',
),
array(
'member_id' => 1,
'member_card_num' => '91001310000057698',
'member_barcode' => '000057698',
)
);
$b = array(
array(
'member_id' => 2,
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
array_walk($a, function($item) use($b) {
echo ($b['0']['member_barcode'] == $item['member_barcode'] ? "found" : NULL);
});
?>
I'd use array_uintersect() to calculate if those multidimensional arrays have a common element:
<?php
$a = array(
array(
'member_id' => '3',
'member_card_num' => '2013011192330791',
'member_barcode' => '2300067628912',
),
array(
'member_id' => '2',
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
$b = array(
array(
'member_id' => '2',
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
$match = array_uintersect($a, $b, function($valueA, $valueB) {
return strcasecmp($valueA['member_barcode'], $valueB['member_barcode']);
});
print_r($match);
Try calling that method as you are looping through Array1 and comparing the user_barcode to every value
You can compare two array this way too:
$per_arr = array();
$permissions = array()
foreach ($per_arr as $key => $perms) {
if(isset($permissions[$key]['name'])){
echo $per_arr[$key]['name']; //matched data
}else{
echo $per_arr[$key]['name']; //not matched data
}
}

To print the value of array.under array

I have to print the all the value of the array written value.
[subscriber] => Array
(
[name] => Subscriber
[capabilities] => Array
(
[read] => 1
[level_0] => 1
)
[default] => Array
(
[deft] => Array (
[one] => 2
[two] => 3
)
[deft_one] => Array (
[one] => t
[two] => h
)
)
)
I have to print each value under the array. So i used a recursion function. But i cant the result. Please help me in recursion function.
Sorry, I am trying till now. Actually i have to print the wp-option table value. There are many serialise array. I want to print all the value individually. I mean when i used the code written bellow i got an array.
function option_value_change () {
global $wpdb;
$myrows = $wpdb->get_results( "SELECT *
FROM `wp_options`");
$temp_url = get_option('siteurl');
$site_url = get_site_url();
foreach ($myrows as $rows){
$option = get_option($rows->option_name);
//print_r($option);
get_option_value($option);
}
}
i can get the table. But in an array. Which array have arrays. So i used an function "get_option_value($option)". as written bellow
function get_option_value($option) {
if(!is_object($option) && !is_array($option)){
echo $option;
}
else{
foreach($option as $option_value){
if(!is_array($option_value)){
echo $option_value;
}
else {
get_option_value($option_value);
}
}
}
}
bUt i cant get all the value. its give an error as
Object of class stdClass could not be converted to string.
So how can i print all the values of the array.
You can use RecursiveArrayIterator example :
$data = array(
'subscriber' => array(
'name' => 'Subscriber',
'capabilities' => array(
'read' => 1,
'level_0' => 1,
),
'default' => array(
'deft' => array(
'one' => 2,
'two' => 3,
),
'deft_one' => array(
'one' => 't',
'two' => 'h',
),
),
),
);
echo "<pre>";
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach($it as $var)
{
echo $var , PHP_EOL ;
}
Output
Subscriber
1
1
2
3
t
h
I didn't test it but you can get the idea;
function printArr($obj){
if(!is_array($obj)){
echo $obj;
return;
}
else if(is_array($obj)){
foreach ($obj as $key => $value) {
printArr($obj[$key]);
}
}
}

Sorting a multi-dimentsional associative array of arrays

Like the title sais I have no idea where to start and using asort() and sort() are not helping in the way I thought it would. Essentially I have an array as such:
$array = array(
'array_c' => array(
'array_b' => (
array('object' => 'e some Object'),
array('object' => 'b some Object'),
),
'array_a' => (
array('object' => 'awesome Object'),
),
),
'array_a' => array(
'array_e' => (
array('object' => 'e some Object'),
),
'array_a' => (
array('object' => 'b awesome Object'),
);
);
);
So I was looking at asort as I want to keep the associations the same, The function I have started writing is:
function sort_me(some_array){
$new_array = asort(some_array);
return $new_array;
}
this function then takes in $array['array_c'] so that you get back an alphabetically sorted array that looks like:
'array_c' => array(
'array_a' => (
array('object' => 'awesome Object'),
),
'array_b' => (
array('object' => 'b some Object'),
array('object' => 'e some Object'),
),
),
can some one tell me why my function is not working? Am I misunderstanding the power of asort?
ksort is the way to go, but ksort does not return a newly sorted array:
http://us.php.net/ksort
it returns a bool -> true if the array could be sorted, otherwise false...
this code snipped should do what you need:
ksort($array);
foreach($array as $key=>$value){
ksort(value);
$array[$key]=$value;
}
print_r($array);

Array containing keys and associative array, how to make a relation

I have an array which contains the path to a specific value from an other array, to make it a bit more clear, here is an exemple.
My array containing the keys which I'll call $params
Array
(
[0] => paths
[1] => assets
[2] => js
)
And here is my associative array which I'll call $config
Array
(
[paths] => Array
(
[assets] => Array
(
[js] => /assets/js
[css] => /assets/css
)
)
[library] => Array
(
[js] => jQuery
)
)
So how could I use my array 1 to access the value in my array 2?
I tried $config[$params[0]][$params[1]][$params[2]], but it's not efficient at all.
You can try
$path = array(
0 => 'paths',
1 => 'assets',
2 => 'js',
);
$data = array(
'paths' => array(
'assets' => array(
'js' => '/assets/js',
'css' => '/assets/css',
),
),
'library' => array(
'js' => 'jQuery',
),
);
$temp = $data;
foreach($path as $key) {
$temp = $temp[$key];
}
var_dump($temp);
Output
string '/assets/js' (length=10)
A loop should solve your problem:
$c = $config;
foreach($params as $path) {
if(!array_key_exists($path, $c)) {
$c = null;
break;
}
$c = $c[$path];
}
This will iterate over every entry in $params and then access the subkey of the $config array. After finding it, $c will contain the current subarray. In the end, $c will contain the value you were looking for (NULL if the path was invalid/not found).
The same can be done in a functional way using the array_reduce function:
$path = array_reduce(function($current, $path) {
if($current == NULL || !array_key_exists($path, $current))
return NULL;
return $current[$path];
}, $params, $config);
Hi Jonathan here you have missed one brace in the end
try this "$config[$params[0]][$params[1]][$params[2]]".
It will work
I am posting a code which worked fine for me
<?php
$params = array(0 => 'paths',1 => 'assets',2 => 'js');
echo '<pre>';print_r($params);
$config = array
(
'paths' => array
(
'assets' => array
(
'js' => '/assets/js',
'css' => '/assets/css'
)
),
'library' => array
(
'js' => 'jQuery'
)
);
echo '<pre>';print_r($config);
echo $config[$params[0]][$params[1]][$params[2]];
?>

Categories