This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 6 years ago.
I have an array of product information. I have a loop that runs through the array and compares the prices to find the lowest one.
$rows = get_field('variations',$product_id);
if($rows){
$prices = array();
foreach($rows as $row){
$prices[] = $row['variation_price'];
}
//Getting the lowest price from the array
$lowest_price = min($prices);
}
echo $lowest_price;
However I now need to get the other information that is associated with the "lowest price" array set. IE. I need the ID of the lowest price product etc.
Any help is welcome!
Here is a dump of the array
Array
(
[0] => Array
(
[] =>
[variation_title] => Small Business
[checkout] => cart
[trial] => Array
(
[0] => trial
)
[variation_price] => 7
[variation_subscription_cycle] => /month
[variation_id] => 405
[variation_url] =>
[custom] => Array
(
[0] => Array
(
[custom_field] => 1 Domain
)
[1] => Array
(
[custom_field] => 1 Million QPM
)
[2] => Array
(
[custom_field] => 50 Records
)
[3] => Array
(
[custom_field] => DNS Alias
)
)
[css_styles] =>
)
[1] => Array
(
[] =>
[variation_title] => Medium Business
[checkout] => cart
[trial] => Array
(
[0] => trial
)
[variation_price] => 35
[variation_subscription_cycle] => /month
[variation_id] => 286
[variation_url] =>
[custom] => Array
(
[0] => Array
(
[custom_field] => 10 Domains
)
[1] => Array
(
[custom_field] => 5 Million QPM
)
[2] => Array
(
[custom_field] => 500 Records
)
[3] => Array
(
[custom_field] => DNS Alias
)
)
[css_styles] => ribbon
)
[2] => Array
(
[] =>
[variation_title] => Large Business
[checkout] => cart
[trial] => Array
(
[0] => trial
)
[variation_price] => 100
[variation_subscription_cycle] => /month
[variation_id] => 406
[variation_url] =>
[custom] => Array
(
[0] => Array
(
[custom_field] => 50 Domains
)
[1] => Array
(
[custom_field] => 15 Million QPM
)
[2] => Array
(
[custom_field] => 1,,500 Records
)
[3] => Array
(
[custom_field] => DNS Alias
)
)
[css_styles] =>
)
)
<?php
class Test {
public $a;
public $b;
public function __construct($a1,$b1)
{
$this->a = $a1;
$this->b = $b1;
}
}
$first = new test(1,12);
$second = new test(4,25);
$third = new test(7,9);
$values = [$first, $second, $third];
function compare (Test $firstObject, Test $secondObject) {
return $firstObject->a > $secondObject->a;
}
usort($values, "compare");
var_dump($values);
?>
Related
I have array value like this
Array
(
[0] => Array
(
[channel] => 15
[id] => clsrnMdVKq2omEuQabSCHp83ezAX6w
)
[1] => Array
(
[channel] => 16
[id] => MfSoHUKjD5n90EZbstpiRGY7e8cgh2
)
[2] => Array
(
[channel] => 17
[id] => MfSoHUKjD5n90EZbstpiRGY7e8cgh2
)
)
Now i want to add another array value in specific index .lets say i wants to add this array value at index 1
[1] => Array
(
[channel] => 20
[id] => xxxxxxxxxxxewqeqwexxxxxxxewrewrw
)
Now the result output should be like this
Array
(
[0] => Array
(
[channel] => 15
[id] => clsrnMdVKq2omEuQabSCHp83ezAX6w
)
[1] => Array
(
[channel] => 20
[id] => xxxxxxxxxxxewqeqwexxxxxxxewrewrw
)
[2] => Array
(
[channel] => 16
[id] => MfSoHUKjD5n90EZbstpiRGY7e8cgh2
)
[3] => Array
(
[channel] => 17
[id] => MfSoHUKjD5n90EZbstpiRGY7e8cgh2
)
)
this is my foreach loop to serlize channel and id
foreach ($channel as $key => $ch) {
$user_hash['channel'] = json_encode($ch);
$user_hash['id'] = random_string('alnum', 30);
array_push($user_hash_array, $user_hash);
}
You need to split the array into 2, then insert your new value at the end of the first sub-array, then merge it with the second sub-array. EG: an array which looks like [1,3,4,5] and you want to insert "2" at position 2, then you split at position one to have [1] and [3,4,5]; then you append "2" at the end of first sub-array to form [1,2], then merge this new subarray with the other sub-array([3,4,5]) to form [1,2] + [3,4,5].
For your implementation, try this code:
$array = array() // the original array you want to modify
$insert = array() // the array you want to push into the original one above
$position = 1 // the position at which you want to insert the new item
$newArray = array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
you can use array_splice array method for add element in array at particular position
<?php
$original_array = array(
array("channel"=>15,"id"=>"sdfdfsf1"),
array("channel"=>16,"id"=>"sdfdfsf2"),
array("channel"=>17,"id"=>"sdfdfsf3")
);
echo "<pre>";print_r($original_array);
$inserted_element =
array(array("channel"=>20,"id"=>"xxxxxxxxxxewqeqwexxxxxxxewrewrw"));
$position=1;
array_splice( $original_array, $position, 0, $inserted_element );
echo "<pre>";print_r($original_array);
?>
Output will be as following
Array
(
[0] => Array
(
[channel] => 15
[id] => sdfdfsf1
)
[1] => Array
(
[channel] => 16
[id] => sdfdfsf2
)
[2] => Array
(
[channel] => 17
[id] => sdfdfsf3
)
)
Array
(
[0] => Array
(
[channel] => 15
[id] => sdfdfsf1
)
[1] => Array
(
[channel] => 20
[id] => xxxxxxxxxxewqeqwexxxxxxxewrewrw
)
[2] => Array
(
[channel] => 16
[id] => sdfdfsf2
)
[3] => Array
(
[channel] => 17
[id] => sdfdfsf3
)
)
I have one array which I am getting from database query response.
Now I want to count same categories and print in option_name array.
I have tried it with different array functions but want get desire output.
I have one idea to take new array and push it with foreach loop but not much idea of how can i achieve using code. Please help me to solve it.
Array
(
[0] => Array
(
[CNC] => Array
(
[id] => 5
[category_id] => 68
)
[GVO] => Array
(
[option_name] => Actors
)
)
[1] => Array
(
[CNC] => Array
(
[id] => 11
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[2] => Array
(
[CNC] => Array
(
[id] => 3
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[3] => Array
(
[CNC] => Array
(
[id] => 4
[category_id] => 74
)
[GVO] => Array
(
[option_name] => Musician
)
)
[4] => Array
(
[CNC] => Array
(
[id] => 7
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
[5] => Array
(
[CNC] => Array
(
[id] => 6
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
)
Desire Output:
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)
Thanks in advance!
You simply need to loop through the array using foreach like as
$result = [];
foreach($arr as $k => $v){
if(isset($result[$v['GVO']['option_name']])){
$result[$v['GVO']['option_name']] += 1;
}else{
$result[$v['GVO']['option_name']] = 1;
}
}
print_R($result);
You can count the option_name values by incrementing a counter in an associative array where the key is the option_name:
$counts = [];
foreach($array as $v) {
if(!isset($counts[$v['GVO']['option_name']])) {
$counts[$v['GVO']['option_name']] = 0;
}
$counts[$v['GVO']['option_name']]++;
}
print_r($counts);
Try this:
$new_arr = array();
foreach(array_column($your_arr, 'option_name') as $value){
if(in_array($value, $new_array)){
$new_array[$value] = $new_array[$value]+1;
}else{
$new_array[$value] = 1;
}
}
Output
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)
Array opareas
(
[0] => Array
(
[name] = => array('opname1')
[subcats] => Array
(
[0] => Array
(
[amount] => 9883
[perc] => 112.61394712853236
)
[1] => Array
(
[amount] => 1
[perc] => 0.011394712853236098
)
[2] => Array
(
[amount] => 3679
[perc] => 41.921148587055605
)
)
)
[1] => Array
(
[name] = => array('opname2')
[subcats] => Array
(
[0] => Array
(
[amount] => 12166
[perc] => 56.8584380987989
)
[1] => Array
(
[amount] => 1473
[perc] => 6.884142636818245
)
[2] => Array
(
[amount] => 955
[perc] => 4.463242510632331
)
[3] => Array
(
[amount] => 6802
[perc] => 31.789503201383372
)
)
)
PHP is excellent for sorting arrays, but I can't figure out what to use when having this issue.. Take a look of the array above.
I want to sort innner subcats[] array by the perc-key from lower to higher.
I want the result to be:
Array opareas
(
[0] => Array
(
[name] = => array('opname1')
[subcats] => Array
(
[0] => Array
(
[amount] => 1
[perc] => 0.011394712853236098 //Lowest percentage value
)
[1] => Array
(
[amount] => 3679
[perc] => 41.921148587055605
)
[2] => Array
(
[amount] => 9883
[perc] => 112.61394712853236 //Highest percentage value
)
)
)
[1] => Array
(
[name] = => array('opname2');
[subcats] => Array
(
[0] => Array
(
[amount] => 955
[perc] => 4.463242510632331 //Lowest percentage value
)
[1] => Array
(
[amount] => 1473
[perc] => 6.884142636818245
)
[2] => Array
(
[amount] => 12166
[perc] => 56.8584380987989
)
[3] => Array
(
[amount] => 6802
[perc] => 31.789503201383372 //Highest percentage value
)
)
)
I've tried with this:
class whateverArray {
private function sort_subcats_perc($a, $b) {
if ($a['subcats']['perc'] == $b['subcats']['perc'] ) {return 0;}
return ( $a['subcats']['perc'] < $b['subcats']['perc'] ) ? -1 : 1;
}
public function showStuff() {
$opareas = array(); //Given above
//Sort subcat array from low to high based on perc-key
uasort( $opareas, array( $this, 'sort_subcats_perc') );
}
);
}
I don't want the actual opareas[0] and operas[1] to switch position (is what happens when using the function I've tried) in the array, I only WANT the inner array subcats[] to change it's order based on perc-field/key. Is this possible with uasort? Or any other builtin of PHP excellent sorting functions?
If you want to sort the sub-array, your comparison function needs to be a bit different. Then you can loop over the outer array by reference, so that the subcats will be sorted in place.
foreach ($opareas as &$value) {
usort($value['subcats'], function($a, $b) {
if ($a['perc'] > $b['perc']) return 1;
if ($a['perc'] < $b['perc']) return -1;
return 0;
});
}
unset($value); // unset the reference after looping
You can use usort. You only need to use uasort if you care about the order of the keys in subcats.
$opareas = array(); //Given above
foreach($opareas as &$oparea){
//Sort subcat array from low to high based on perc-key
uasort( $oparea, array( $this, 'sort_subcats_perc') );
}
can be the solution here.
and i got a problem (its big for me) :(
ok, i have some array like ...
Array(
[0] => Array
(
[id] => 1
[order_sn] => EU/2011/04/PO/5
[total] => 65
)
[1] => Array
(
[id] => 1
[order_sn] => EU/2011/04/RS/4
[total] => 230
)
[2] => Array
(
[id] => 1
[order_sn] => EU/2011/04/RS/3
[total] => 130
)
[3] => Array
(
[id] => 2
[order_sn] => EU/2011/04/RS/2
[total] => 100
)
[4] => Array
(
[id] => 2
[order_sn] => EU/2011/04/RS/1
[total] => 60
)
)
how to merge them if the array have same key value ... ?
the result that i need got is like this ...
Array(
[0] => Array
(
[id] => 1
[detail] => Array
(
[0] => Array
(
[order_sn] => EU/2011/04/PO/5
[total] => 65
)
[1] => Array
(
[order_sn] => EU/2011/04/RS/4
[total] => 230
)
[2] => Array
(
[order_sn] => EU/2011/04/RS/3
[total] => 130
)
)
)
[2] => Array
(
[id] => 2
[detail] => Array
(
[0] => Array
(
[order_sn] => EU/2011/04/RS/2
[total] => 100
)
[1] => Array
(
[order_sn] => EU/2011/04/RS/1
[total] => 60
)
)
)
)
im very need some help here, and im working on PHP ... what method should i do for this case?
i try too searching on google and in here ... but i dont know the keyword >.<
Many thanks before :)
regard, Stecy
Try like this:
<?php
$result = array();
foreach ($my_array as $v) {
$id = $v['id'];
$result[$id]['id'] = $id;
$result[$id]['detail'][] = array(
'order_sn' => $v['order_sn'],
'total' => $v['total'],
);
}
You can just loop over the array and build a resulting one:
// $a is your array
$r=array();
foreach($a as $v)
$r[$v['id']][]=array('order_sn'=>$v['order_sn'], 'total'=>$v['total']);
echo'<pre>';
var_dump($r);
Since you do the paring by ID, it is wise to have it as the key and all the data associated with it as the value. There's no need to also have id and detail.
foreach($origianlArray as $key => $value){
$newArray[$value['id']]['id'] = $value['id'];
$newArray[$value['id']]['detail'][] = array('order_sn' => $value['order_sn'], 'total' => $value['total']);
}
Check out the PHP array_merge function.
I have following arrays:
1) for total placed
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totalplaced] => 8
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totalplaced] => 1
)
)
)
2) for total working
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totalworking] => 4
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totalworking] => 1
)
)
)
3) for total trained
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totaltrained] => 8
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totaltrained] => 1
)
)
)
I wanted to merge these arrays so that the resultant array should look like this
[newarray] => Array(
[0] => Array (
[centers] => Array
(
[name] => delhi
[id] => 1
[totalplaced] => 8
[totalworking] => 4
[totaltrained] => 8
)
)
[1]=> Array(
[centers] => Array
(
[name] => mumbai
[id] => 2
[totalplaced] => 1
[totalworking] => 1
[totaltrained] => 1
)
)
)
This is the tabular representation of the above data which i want to display
centername totalplaced totalworking totaltrained
delhi 8 4 8
mumbai 1 1 1
Please help me on this.
Thanks
Pankaj Khurana
The difficulty here is that PHP's functions such as array_merge() and array_merge_recursive() will not merge data into numeric keys, but rather will re-key any duplicate numeric key. So for example given two arrays:
array(
'test' => 'abc',
0 => 'xyz'
);
array(
'test' => 'def',
0 => 'uvw'
);
Merging them together with array_merge() will produce an array like:
array(
'test' => 'def',
0 => 'xyz',
1 => 'uvw'
);
So, you need a custom function to be "additive" on any key, regardless of whether it is a string or numeric key. Try this:
function mixed_key_array_merge() {
$args = func_get_args();
$result = array();
foreach ($args as $arg) {
// discard non-array arguments; maybe this could be better handled
if (!is_array($arg)) {
continue;
}
foreach ($arg as $key => $value) {
if (!isset($result[$key])) {
$result[$key] = $value;
} else if (is_array($result[$key])) {
$result[$key] = call_user_func_array('mixed_key_array_merge',array($result[$key],$value));
}
}
}
return $result;
}