Sort PHP array by numerical values - php

I would like to sort the following names
Array ( [Jessie] => 2 [Sarah] => 3 [Simon] => 2 [John] => 2 [Kevin] => 1 [Canvasser] => 8 [canvasser] => 11 )
based on the values corresponding to them
I printed the names through the following function
// get canvasser individual names and count houses canvassed
foreach ($canvassers as $key => $value) {
// Add to the current group count if it exists
if ( isset( $canvasser_counts[$value] ) ) {
$canvasser_counts[$value]++;
}
// or initialize to 1 if it doesn't exist
else {
$canvasser_counts[$value] = 1;
}
}
print_r($canvasser_counts);
where $canvassers simply held all the names eg.
$canvassers = array('Jessie', 'Simon', 'Jessie')
Any help would be really appreciated, I have spent so long on this but can't get my head straight to sort the array correctly.

You want to use asort() - http://php.net/manual/en/function.asort.php - to sort the values in ascending order, or arsort() - http://php.net/manual/en/function.arsort.php - to sort in descending order.
Given this PHP:
$vals = array("Jessie" => 2, "Sara" => 3, "Simon" => 2, "John" => 2, "Kevin" => 1, "Canvasser" => 8, "canvasser" => 11 );
print_r($vals); // current order
asort($vals); // sort array
print_r($vals); // new order
You will get the following output:
Array
(
[Jessie] => 2
[Sara] => 3
[Simon] => 2
[John] => 2
[Kevin] => 1
[Canvasser] => 8
[canvasser] => 11
)
Array
(
[Kevin] => 1
[Jessie] => 2
[John] => 2
[Simon] => 2
[Sara] => 3
[Canvasser] => 8
[canvasser] => 11
)

Related

Sum parts of an array in php

this is quite beyond me. Appreciate some help.
I have an array in php like so:
[0] => Array
(
[cust_id] => 1006
[no_of_subs] => 2
[dlv_id] => 1000
)
[1] => Array
(
[cust_id] => 1011
[no_of_subs] => 3
[dlv_id] => 1000
)
[2] => Array
(
[cust_id] => 1012
[no_of_subs] => 5
[dlv_id] => 1001
)
[3] => Array
(
[cust_id] => 1013
[no_of_subs] => 6
[dlv_id] => 1001
)
I don't need the cust_id field. I just need to group the dlv_id and the sum of no_of_subs for each matching dlv_id. The result should look like this:
[0] => Array
(
[dlv_id] => 1000
[no_of_subs] => 5
)
[1] => Array
(
[cust_id] => 1011
[no_of_subs] => 11
)
Thank you for any help.
I don't understand the downvotes for this question. Am i doing it all wrong? Downvoting without a reason is not helping.
The simplest, most efficient way to group and sum is to perform a single loop and assign temporary associative keys.
When a row is identified as a new dlv_id row, save the two desired elements, otherwise add the no_of_subs value to the pre-existing value.
Optionally, remove the temporary keys with array_values().
Code (Demo)
$array = [
["cust_id" => 1006, "no_of_subs" => 2, "dlv_id" => 1000],
["cust_id" => 1011, "no_of_subs" => 3, "dlv_id" => 1000],
["cust_id" => 1012, "no_of_subs" => 5, "dlv_id" => 1001],
["cust_id" => 1013, "no_of_subs" => 6, "dlv_id" => 1001]
];
foreach ($array as $row) {
if (!isset($result[$row["dlv_id"]])) {
$result[$row["dlv_id"]] = ["dlv_id" => $row["dlv_id"], "no_of_subs" => $row["no_of_subs"]];
} else {
$result[$row["dlv_id"]]["no_of_subs"] += $row["no_of_subs"];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'dlv_id' => 1000,
'no_of_subs' => 5,
),
1 =>
array (
'dlv_id' => 1001,
'no_of_subs' => 11,
),
)
Using array_column function, we can extract out dlv_id and no_of_subs separately in two different arrays, using cust_id as the key.
Now, simply loop over the array of dlv_id, and if matching key found, add the no_of_subs to it, else set the value (for the first time).
We use isset function to check if the key exists already or not.
Try the following:
// your input array is $input_array
// get all dlv_id maintaining the cust_id as index
$dlv_id = array_column($input_array, 'dlv_id', 'cust_id');
// get all no_of_subs maintaining the cust_id as index
$no_of_subs = array_column($input_array, 'no_of_subs', 'cust_id');
$output = array();
foreach ($dlv_id as $key => $value) {
if (isset($output[$value]['dlv_id'])) {
$output[$value]['dlv_id'] += $no_of_subs[$key];
} else {
$output[$value]['dlv_id'] += $no_of_subs[$key];
}
}

Group rows by one column and populate subarray within group with another column's value

I have an array coming from my database and simply it consists of questions and answers. I am trying to merge 2 arrays and create multidimensional array if values are more than one.
Array
(
[0] => Array
(
[question_id] => 1
[option_id] => 1
)
[1] => Array
(
[question_id] => 2
[option_id] => 3
)
[2] => Array
(
[question_id] => 3
[option_id] => 5
)
[3] => Array
(
[question_id] => 3
[option_id] => 6
)
)
I've tried to separate answers and questions to 2 different arrays but couldn't figure how to merge them again.
$user_questions = array_column($answers, 'question_id');
$user_answers = array_column($answers, 'option_id');
What I need is (question 3 has 2 answers) :
Array
(
[1] => 1
[2] => 3
[3] => Array (5, 6)
)
You can group your data like this as you fetch the results from your query instead of processing it after the fact. To get the array you have now, you're currently doing something like this:
while ($row = $stmt->someFetchMethod()) {
$result[] = $row;
}
Instead, use the question id as the key in your result array, and append the option id to an array at that key.
while ($row = $stmt->someFetchMethod()) {
$result[$row['question_id']][] = $row['option_id'];
}
Below code will create a new array by looping the existing array.
// Considering your existing array to be like this
$array = array(
'0' => array('question_id' => 1,'option_id' => 1),
'1' => array('question_id' => 2, 'option_id' => 3 ),
'2' => array('question_id' => 3,'option_id' => 5),
'3' => array('question_id' => 3,'option_id' => 6)
);
//define new array
$new_array = array();
// loop the array
foreach($array as $key=>$value){
// if the option/answer is already set to to question key
if(isset($new_array[$value['question_id']])){
// if question key is an array, push new option to that array
if(is_array($new_array[$value['question_id']])){
array_push($new_array[$value['question_id']], $value['option_id']);
}else{
// convert question key to array with the old value and new option value
$new_array[$value['question_id']] = array($new_array[$value['question_id']],$value['option_id']);
}
}
else{
// assing option as value to question key
$new_array[$value['question_id']] = $value['option_id'];
}
}
print_r($new_array);
Out put:
Array
(
[1] => 1
[2] => 3
[3] => Array
(
[0] => 5
[1] => 6
)
)

combine or intersect two arrays different length in php

First array is $niz:
Array (
[Swansea] => 4
[Stoke City] => 3
[Sunderland] => 3
[Southampton] => 5
[Liverpool] => 3
[Manchester United] => 2
[Hull City] => 1
[Tottenham] => 2
[Newcastle Utd] => 1
[Aston Villa] => 1
[West Ham] => 2
[Crystal Palace] => 3
[Chelsea] => 3
)
Second array is $niz1:
Array (
[Stoke City] => 2
[Sunderland] => 2
[Liverpool] => 1
[Hull City] => 1
[Tottenham] => 1
[Manchester United] => 1
[Newcastle Utd] => 1
[Crystal Palace] => 3
[Chelsea] => 1
)
How to combine these arrays to get $niz2 (keys are ordered like array $niz1 and values are from matching array $niz) like:
$niz2:
Array (
[Stoke City] => 3
[Sunderland] => 3
[Liverpool] => 3
[Hull City] => 1
[Tottenham] => 2
[Manchester United] => 2
[Newcastle Utd] => 1
[Crystal Palace] => 3
[Chelsea] => 3
)
I tried with function array_merge() but I get empty values and I tried with array_intersect_key().
try this
foreach ($niz1 as $k=>$n)
{
if(in_array($k,$niz1))
{
$niz2[$k]=$niz[$k];
}
}
print_r($niz2);
Try this:
$temp = array_intersect_key($niz, $niz1);
foreach ($niz1 as $k => $v) {
$niz2[$k] = $temp[$k];
}
//(overwrites the values of $niz1 with those of $niz2)
$bif=array_merge($niz1,$niz);
//(removes everything from $bif that is not in $niz1)
$result=array_intersect($niz1,$bif);

Splitting one Array into many Array in PHP

I'm in need of splitting of the single array into multiple array for some report generating purpose.
I have an array like this which I have given below.
Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
I want to split the above to,
Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
)
Array
(
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
)
Array
(
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
How can I do this in PHP ??
$oldarray=array('blah_1'=>1,'blahblah_1'=>31,'blahblahblah_1'=>25,
'blah_3'=>1,'blahblah_3'=>3,'blahblahblah_3'=>5,
'blah_10'=>1,'blahblah_10'=>10,'blahblahblah_10'=>2
)
$newarray=array();
foreach ($oldarray as $key=>$val) { //Loops through each element in your original array
$parts=array_reverse(explode('_',$key)); //Splits the key around _ and reverses
$newarray[$parts[0]][$key]=$val; //Gets the first part (the number) and adds the
//value to a new array based on this number.
}
The output will be:
Array (
[1]=>Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
)
[3]=>Array
(
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
)
[10]=>Array
(
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
)
Use array_chunk. Example:
<?php
$chunks = array_chunk($yourarray, 3);
print_r($chunks);
?>
Use array_chunk
i.e
$a = array(1,2,3,4,5,6,7);
var_dump(array_chunk($a, 3));
Not sure if you are looking for array_slice
but take a look at this example:
<?php
$input = array("a", "b", "c", "d", "e");
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
will result in this:
Array
(
[0] => c
[1] => d
)
Array
(
[2] => c
[3] => d
)
array_chunk ( array $input , int $size);

PHP split array based on search results

I have a multidimensional array which is created by a MySQL query which collects results based on a number of groups and sums. The array is below.
I'm interested in the costtotal and hitcount for each type of 'ad_type', 'click_status' and 'link_status' variation.
The possible values of the 3 types of variable are known:
i.e.
ad_type 0 / 1
click_status 2 / 3
link_status 1 / 2
I would like to create a new array based on the results of each combination.
I'm guessing a search or split would do it but I'm not having much luck.
How would I go about doing this?
Array
(
[0.261346210037681] => Array
(
[costtotal] => 0.0015
[hitcount] => 1
[ad_type] => 0
[click_status] => 2
[link_status] => 1
)
[0.190427019438173] => Array
(
[costtotal] => 0.001
[hitcount] => 1
[ad_type] => 0
[click_status] => 3
[link_status] => 1
)
[0.563596305962276] => Array
(
[costtotal] => 0.007
[hitcount] => 5
[ad_type] => 1
[click_status] => 2
[link_status] => 1
)
[0.893211513658251] => Array
(
[costtotal] => 0
[hitcount] => 3
[ad_type] => 1
[click_status] => 2
[link_status] => 2
)
[0.209184847035617] => Array
(
[costtotal] => 0.004
[hitcount] => 2
[ad_type] => 1
[click_status] => 3
[link_status] => 1
)
[0.73545002260753] => Array
(
[costtotal] => 0
[hitcount] => 1
[ad_type] => 1
[click_status] => 3
[link_status] => 2
)
)
If I fully understand what you want, then this code should satisfy you:
function generateClickCounterInfo() {
return array(
'costTotal' => 0.0,
'hitCount' => 0
);
}
function generateLinkStatusStructure() {
return array(
1 => generateClickCounterInfo(),
2 => generateClickCounterInfo()
);
}
function generateClickStatusStructure() {
return array(
2 => generateLinkStatusStructure(),
3 => generateLinkStatusStructure()
);
}
function generateAdTypeArrayStructure() {
return array(
0 => generateClickStatusStructure(),
1 => generateClickStatusStructure()
);
}
function getClickCounterReport(array $data) {
$result = generateAdTypeArrayStructure();
foreach ($data as $key => $value) {
$adType = $value['ad_type'];
$clickStatus = $value['click_status'];
$linkStatus = $value['link_status'];
if (!isset($result[$adType])
|| !isset($result[$adType][$clickStatus])
|| !isset($result[$adType][$clickStatus][$linkStatus])) {
throw new Exception(
"Input data does not conform to expected format. " .
"ad_type = {$adType}, click_status = {$clickStatus}, link_status = ${linkStatus}"
);
}
$costTotal = $value['costtotal'];
$hitCount = $value['hitcount'];
$result[$adType][$clickStatus][$linkStatus]['costTotal'] += $costTotal;
$result[$adType][$clickStatus][$linkStatus]['hitCount'] += $hitCount;
}
return $result;
}
And than getClickCounterReport($data) (where $data is data provided by you) will produce following array: http://pastebin.ubuntu.com/607464/
P.S. Knowing disadvantages:
No OOP (but these functions will be easy to transform to methods)
Magick numbers (0, 1, 2, 3 etc)
No array splitting is necessary. Simply create the variables that will store the totals for each of the permutation you want to measure and iterate through your array. Add to appropriate variables based upon the value you observe in ad_type, click_status, and link_status.

Categories