Group array by keys value - php

I have searched around and I am at my wits end so I will make this easy. This is what I have in a print_r:
Array
(
[0] => Array
(
[name] => client interaction
[y] => 2.7
)
[1] => Array
(
[name] => client interaction
[y] => 0.1
)
[2] => Array
(
[name] => project planning
[y] => 0.1
)
[3] => Array
(
[name] => client interaction
[y] => 5.9
)
)
And this is what I want it to be:
Array
(
[0] => Array
(
[name] => client interaction
[y] => 8.7
)
[1] => Array
(
[name] => project planning
[y] => 0.1
)
)

Is it absolutely necessary that your desired array use numeric indeces? If I were to do this I would do it this way (not the same as your desired array though)
$newArray = array();
foreach($array as $item)
{
if(!isset($newArray[$item["name"]]))
$newArray[$item["name"]] = 0;
$newArray[$item["name"]] += $item["y"];
}
This will give you an array of this structure:
Array
(
[client interaction] => 8.7
[project planning] => 0.1
)
To get the keys back you simply use the second form of the foreach loop
foreach($newArray as $name => $y)
$name will contain the name and $y the y in your original array.

$hash = array();
foreach ($sourceArray as $key=>$value) {
$y = 0;
if (isset($hash{$value{'name'}})) {
$y = $hash{$value{'name'}};
}
$hash{$value{'name'}} = $y + $value{'y'};
}
$result = array();
foreach ($hash as $key => $value) {
$result[] = array( 'name' => $key, 'value' => $value );
}
print_r($result);
The last loop is just to get $hash into the exact format you specified.
Explanation:
$hash
Is a temporary structure used to compute the sums for each unique name.
foreach ($sourceArray as $key=>$value) {
This goes through your original array ($sourceArray) and pulls out each element.
$y = 0;
Initializes a variable to store the current sum that belongs with that name.
if (isset($hash{$value{'name'}})) {
Checks to see if a value has already been stored in $hash for the given name.
$y = $hash{$value{'name'}};
}
Sets $y to the previously calculated sum for the given name, if there was one.
$hash{$value{'name'}} = $y + $value{'y'};
}
Stores the sum for the given name into our temporary structure $hash.
$result = array();
foreach ($hash as $key => $value) {
$result[] = array( 'name' => $key, 'value' => $value );
}
converts $hash to the format you desired.
The empy []'s in $result[] = ... add the right hand side of the expression to the end of the $result array.

$mixed = array(); // Should contain your array shown above
$groups = array();
$newArray = array(); // Will contain your new array
$counter = 0;
foreach( $mixed as $mix )
{
if ( isset($groups[$mix['name']]) )
{
$newArray[$groups[$mix['name']]]['y'] += $mix['y'];
}
else
{
$groups[$mix['name']] = $counter;
$newArray[] = $mix;
$counter++;
}
}
http://codepad.org/EjdHxgvt

Related

Group data by leading portion of keys and push values into each group as indexed elements

I have the following working code that from 2 separate arrays ($I & $f) creates final multidimension array with the data as associated columns.
The problem is i feel the code is clunky, but i cant see if, or how it could me improved. So I'm hoping a second pair of eyes can help.
<?php
//main array of input data
$i = [ 'input_tickettype1_storeno_00' => null,
'input_tickettype1_deliverydate_00' => null,
'input_tickettype1_ticketref_00' => null,
'input_tickettype1_storeno_01' => '9874',
'input_tickettype1_deliverydate_01' => '2022-02-01',
'input_tickettype1_ticketref_01' => 'EDN6547',
'input_tickettype1_storeno_02' => '8547',
'input_tickettype1_deliverydate_02' => '2022-01-31',
'input_tickettype1_ticketref_02' => 'EDN5473',
'input_tickettype1_storeno_03' => '9214',
'input_tickettype1_deliverydate_03' => '2022-02-28',
'input_tickettype1_ticketref_03' => 'EDN1073'
];
//headers
$h = [ 'input_tickettype1_storeno' ,
'input_tickettype1_deliverydate',
'input_tickettype1_ticketref'
];
//final multidim array
$f = array();
//Create a multidim for the headers and the values
foreach ($h as $k => $v)
{
$f[] = [$v=>null];
}
//loop throught the headers looping for matches in the input data
for ($x = 0; $x < count($f); $x++) {
foreach ($f[$x] as $fk => $fv) {
foreach ($i as $ik => $iv) {
if (str_contains($ik,$fk)) {
array_push($f[$x],$iv);
}
}
}
}
print_r($f);
//Actual Working Output
// Array (
// [0] => Array ( [input_tickettype1_storeno] =>
// [0] =>
// [1] => 9874
// [2] => 8547
// [3] => 9214
// )
// [1] => Array ( [input_tickettype1_deliverydate] =>
// [0] =>
// [1] => 2022-02-01
// [2] => 2022-01-31
// [3] => 2022-02-28
// )
// [2] => Array ( [input_tickettype1_ticketref] =>
// [0] =>
// [1] => EDN6547
// [2] => EDN5473
// [3] => EDN1073
// )
// )
?>
Yes, indeed I think the code can be optimised for readability and logic.
I can think of two methods you can use.
Method 1 : nested foreach
First of all, you don't need a foreach to initialize your multidimentional array, you can do it within the main loop you use to read the data. So you can remove the foreach -- $f[] = [$v=>null];
Then, instead of having 1 for and 2 foreach you can just have 2 foreach one for each array and use a very fast strpos to identify if the key matches and populate the final array.
Here's the resulting code.
$f = [];
foreach ($h as $prefix) {
$f[$prefix] = [];
foreach ($i as $key => $val) {
if (strpos($key, $prefix) === 0) {
$f[$prefix][] = $val;
}
}
}
This first method is simple, with a straightforward logic. However it requires a nested foreach. Which means that if both arrays get larger, your code gets much slower.
Method 2 : key manipulation
This method assumes that the keys of the first array never change structure and they are always somestringid_[digits]
In this case we can avoid looping the second array and just use a regular expression to recreate the key.
$f = [];
foreach ($i as $key => $value) {
preg_match('/^(.*)_[0-9]+$/', $key, $m);
$key = $m[1];
if (empty($f[$m[1]])) {
$f[$m[1]] = [];
}
$f[$m[1]][] = $value;
}
I don't see any need to implement any additional data or conditions. You only need to read your main array, mutate the keys (trim the trailing unique identifiers) as you iterate, and push data into their relative groups.
Code: (Demo)
$result = [];
foreach ($array as $k => $v) {
$result[preg_replace('/_\d+$/', '', $k)][] = $v;
}
var_export($result);
Output:
array (
'input_tickettype1_storeno' =>
array (
0 => NULL,
1 => '9874',
2 => '8547',
3 => '9214',
),
'input_tickettype1_deliverydate' =>
array (
0 => NULL,
1 => '2022-02-01',
2 => '2022-01-31',
3 => '2022-02-28',
),
'input_tickettype1_ticketref' =>
array (
0 => NULL,
1 => 'EDN6547',
2 => 'EDN5473',
3 => 'EDN1073',
),
)

Iterating a Multidimensional Array

I'm having trouble correctly iterating a multi-dimension array I am trying to retrieve the values for each well..value.
My Issue is I seem to have an array within an array which has an array for each key/pair value, I'm unsure how to loop through these and add the values to the database for each array.
Eg, if I have one form on my page the array return is below and further below that is what is returned with two forms etc
Array
(
[0] => Array
(
[0] => Array
(
[name] => sl_propid
[value] => 21
)
[1] => Array
(
[name] => sl_date
[value] => 04/01/2014
)
[2] => Array
(
[name] => sl_ref
[value] => Form1
)
[3] => Array
(
[name] => sl_nom_id
[value] => 12
)
[4] => Array
(
[name] => sl_desc
[value] => Form1
)
[5] => Array
(
[name] => sl_vat
[value] => 60
)
[6] => Array
(
[name] => sl_net
[value] => 999
)
)
)
My question is how do I iterate through the returned array no matter it's size and pull back each value?
I have tried nesting foreach loops, which did give me results, but only for one key/value pair which leads me to believe I'm doing the looping wrong, I can retrieve the values if I statically access them, which is of course no use normally.
foreach ($result as $array) {
print_r($array);
}
the above foreach returns the above arrays, adding another foreach removes the out "container" array but adding another foreach loop, returns only one key/value pair, which sort makes sense because the first index is an array, too, hope I haven't confused everyone else as much as already have myself D:.
Thank you for reading
Any help appreciated.
EDIT Using the below array walk recursive I get the output
$result = $this->input->post();
function test_print($item, $key)
{
echo "$key holds $item\n";
//$this->SalesLedgerModel->addInvoiceToLedger($key, $key, $key, $key, $key, $key, $key);
}
array_walk_recursive($result, 'test_print');
}
Which is almost what I want but how do I take each individual value and add it to my ModelFunction (to actually input the data to DB)
The function takes 7 parameters but I am unsure how to make sure the right info goes to the correct parameter
$this->SalesLedgerModel->addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net);
My Controller function
function addInvoiceToLedger(){
$this->load->model('SalesLedgerModel');
// $propid = $this->input->post('propid');
// $date = $this->input->post('date');
// $ref = $this->input->post('ref');
// $nomid = $this->input->post('id');
// $desc = $this->input->post('desc');
// $vat = $this->input->post('vat');
// $net = $this->input->post('sl_net');
$results = $this->input->post();
//var_dump($results);
$size1 = sizeof($results)-1;
for($i=0; $i<=$size1; $i++)
{
$size2 = sizeof($results[$i])-1;
for($j=0; $j<=$size2; $j++)
{
$name = $results[$i][$j]['name'];
$value = $results[$i][$j]['value'];
echo $value . "\n" ;
$this->SalesLedgerModel->addInvoiceToLedger($value, $value, $value, $value, $value, $value, $value);
}
}
My Model function
function addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net){
$data = array('sl_prop_id' => $propid, 'sl_date' => $date,
'sl_ref' => $ref, 'sl_nominal_sub' => $nomid, 'sl_invoice_desc' => $desc, 'sl_vat' => $vat, 'sl_amount' => $net);
$this->db->insert('salesledger', $data);
}
You can either write some recursive code to step through the array and call itself again if an element turns into an array, or write a very simple function and call it via array walk recursive which will then let you do whatever you like with the value:
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
?>
Output:
a holds apple
b holds banana
sour holds lemon
Try this. It'll be much faster. Since 3 foreach loops is much costlier than 2 for loops (for loops are faster than foreach loops) -
$size1 = sizeof($results)-1;
if($size1 > 0)
{
for($i=0; $i<=$size1; $i++)
{
$size2 = sizeof($results[$i])-1;
if($size2 > 0)
{
for($j=0; $j<=$size2; $j++)
{
$name = $results[$i][$j]['name'];
$value = $results[$i][$j]['value'];
$insert = $this->your_model->insert($name, $value);
}
}
}
}
foreach ($result as $array) {
foreach($array as $arr){
foreach($arr as $a){
echo $a[value];
}
}
}

Getting multi dimensional array to create new arrays based on index value

I am having a terrible time getting this to work I have been struggling with it for a couple hours now. Can someone please help me? I have included a fiddle.
I believe my problem is in this string:
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
Basically I have the following multidimensional array:
[sales] => Array
(
[FirstName] => Array
(
[0] => salesFirst1
[1] => salesFirst2
)
[LastName] => Array
(
[0] => salesLast1
[1] => salesLast2
)
)
[decisionmaker] => Array
(
[FirstName] => Array
(
[0] => dmFirst1
[1] => dmFirst2
)
[LastName] => Array
(
[0] => dmLast1
[1] => dmLast2
)
)
)
I need this to be reorganized like I did with the following array:
Array
(
[additionallocations0] => Array
(
[Address] => Address1
[State] => State1
)
[additionallocations1] => Array
(
[Address] => Address2
[State] => State2
)
)
Here is the original:
Array
(
[additionallocations] => Array
(
[Address] => Array
(
[0] => Address1
[1] => Address2
)
[State] => Array
(
[0] => State1
[1] => State2
)
)
This is how I reorganize the above array:
if(isset($_POST['additionallocations'])) {
$qty = count($_POST['additionallocations']["Address"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST['additionallocations'] as $param => $values)
{
$additional['additionallocations'.$l][$param] = $values[$l];
}
}
And this is what I am using for the sales and decisionmaker array. If you notice I have an array that contains sales and decisionmaker in it. I would like to be able to sort any future arrays by just adding its primary arrays name. I feel I am close to solving my problem but I can not get it to produce right.
$salesAndOwner = array(0 => "sales", 1 => "decisionmaker");
for($i = 0; $i < 2; $i++){
$qty = count($_POST[$salesAndOwner[$i]]["FirstName"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST[$salesAndOwner[$i]] as $param => $values)
{
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
}
}
}
In the above code I hard coded 'sales' into the variable I need it to make a variable name dynamically that contains the sales0 decisionmaker0 and sales1 decisionmaker1 arrays so $sales and $decisionmaker
I hope this makes sense please let me know if you need any more info
Let's break it down. Using friendly variable names and spacing will make your code a lot easier to read.
Remember. The syntax is for you to read and understand easily. (Not even just you, but maybe future developers after you!)
So you have an array of groups. Each group contains an array of attributes. Each attribute row contains a number of attribute values.
PHP's foreach is a fantastic way to iterate through this, because you will need to iterate through (and use) the index names of the arrays:
<?php
$new_array = array();
// For each group:
foreach($original_array as $group_name => $group) {
// $group_name = e.g 'sales'
// For each attribute in this group:
foreach($group as $attribute_name => $attributes) {
// $attribute_name = e.g. 'FirstName'
// For each attribute value in this attribute set.
foreach($attributes as $row_number => $attribute) {
// E.g. sales0
$row_key = $group_name . $row_number;
// if this is the first iteration, we need to declare the array.
if(!isset($new_array[$row_key])) {
$new_array[$row_key] = array();
}
// e.g. Array[sales0][FirstName]
$new_array[$row_key][$attribute_name] = $attribute;
}
}
}
?>
With this said, this sort of conversion may cause unexpected results without sufficient validation.
Make sure the input array is valid (e.g. each attribute group has the same number of rows per group) and you should be okay.
$salesAndOwner = array("sales", "decisionmaker");
$result = array();
foreach ($salesAndOwner as $key) {
$group = $_POST[$key];
$subkeys = array_keys($group);
$first_key = $subkeys[0];
foreach ($group[$first_key] as $i => $val) {
$prefix = $key . $i;
foreach ($subkeys as $subkey) {
if (!isset($result[$prefix])) {
$result[$prefix] = array();
}
$result[$prefix][$subkey] = $val;
}
}
}
DEMO
Try
$result =array();
foreach($arr as $key=>$val){
foreach($val as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$result[$key.$key2][$key1] = $val2;
}
}
}
See demo here

parsing out the last number of the post

Ok so i have a post that looks kind of this
[optional_premium_1] => Array
(
[0] => 61
)
[optional_premium_2] => Array
(
[0] => 55
)
[optional_premium_3] => Array
(
[0] => 55
)
[premium_1] => Array
(
[0] => 33
)
[premium_2] => Array
(
[0] => 36 )
[premium_3] => Array
(
[0] => 88 )
[premium_4] => Array
(
[0] => 51
)
how do i get the highest number out of the that. So for example, the optional "optional_premium_" highest is 3 and the "premium_" optional the highest is 4. How do i find the highest in this $_POST
You could use array_key_exists(), perhaps something like this:
function getHighest($variableNamePrefix, array $arrayToCheck) {
$continue = true;
$highest = 0;
while($continue) {
if (!array_key_exists($variableNamePrefix . "_" . ($highest + 1) , $arrayToCheck)) {
$continue = false;
} else {
highest++;
}
}
//If 0 is returned than nothing was set for $variableNamePrefix
return $highest;
}
$highestOptionalPremium = getHighest('optional_premium', $_POST);
$highestPremium = getHighest('premium', $_POST);
I have 1 question with 2 parts before I answer, and that is why are you using embedded arrays? Your post would be much simpler if you used a standard notation like:
$_POST['form_input_name'] = 'whatever';
unless you are specifically building this post with arrays for some reason. That way you could use the array key as the variable name and the array value normally.
So given:
$arr = array(
"optional_premium_1" => "61"
"optional_premium_2" => "55"
);
you could use
$key = array_keys($arr);
//gets the keys for that array
//then loop through get raw values
foreach($key as $val){
str_replace("optional_premium_", '', $val);
}
//then loop through again to compare each one
$highest = 0;
for each($key as $val){
if ((int)$val > $highest) $highest = (int)$val;
}
that should get you the highest one, but then you have to go back and compare them to do whatever your end plan for it was.
You could also break those into 2 separate arrays and assuming they are added in order just use end() http://php.net/manual/en/function.end.php
Loop through all POST array elements, pick out elements having key names matching "name_number" pattern and save the ones having the largest number portion of the key names. Here is a PHP script which does it:
<?php // test.php 20110428_0900
// Build temporary array to simulate $_POST
$TEMP_POST = array(
"optional_premium_1" => array(61),
"optional_premium_2" => array(55),
"optional_premium_3" => array(55),
"premium_1" => array(33),
"premium_2" => array(36),
"premium_3" => array(88),
"premium_4" => array(51),
);
$names = array(); // Array of POST variable names
// loop through all POST array elements
foreach ($TEMP_POST as $k => $v) {
// Process only elements with names matching "word_number" pattern.
if (preg_match('/^(\w+)_(\d+)$/', $k, $m)) {
$name = $m[1];
$number = (int)$m[2];
if (!isset($names[$name]))
{ // Add new POST var key name to names array
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
} elseif ($number > $names[$name]['max_num'])
{ // New largest number in key name.
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
}
}
}
print_r($names);
?>
Here is the output from the script:
Array
(
[optional_premium] => Array
(
[name] => optional_premium
[max_num] => 3
[key_name] => optional_premium_3
[value] => Array
(
[0] => 55
)
)
[premium] => Array
(
[name] => premium
[max_num] => 4
[key_name] => premium_4
[value] => Array
(
[0] => 51
)
)
)
Though ineffective, you could try something like
$largest = 0;
foreach($_POST as $key => $value)
{
$len = strlen("optional_premium_");
$num = substr($key, $len);
if($num > $largest)
$largest = $num;
}
print_r($largest);
The problem being that this will only work for one set of categories. It will most likely give errors throughout the script.
Ideally, you would want to reorganize your post, make each array be something like
[optional_premium_1] => Array
(
[0] => 61
["key"] => 1
)
[optional_premium_2] => Array
(
[0] => 61
["key"] => 2
)
Then just foreach and use $array["key"] to search.

Nested for each's looping through multi-dimensional array - how to do a conditional on the last value

After a rollercoaster ride, I am "this" close to finalising a script I have been working on.
I have a multi-dimensional array stored in $newarray as below. I have built this array myself so the code to build it can be changed if needs be. But after creation I then loop through it picking out the values I want. I build a new array for each key in the upper array (3 in this case, 111, 222 & 333) and populate each with a a bunch of data objects from next array key down along with some other data.
However, what I need in the case below is to generate each of the 3 arrays (111, 222, 333) twice, once where the final array value = 0 ($the_action) and once where it = '1'. Where it = 1, print it, else where it = 0, do something else.
I also think that the way I loop through arrays with a single value in it is probably not very efficient, and the same goes for using key names as values.
Grateful for any help.
Array
(
[111] => Array
(
[1234] => Array
(
[100000] => Array
(
[20000] => 0
)
)
[1244] => Array
(
[100001] => Array
(
[20001] => 1
)
)
[1255] => Array
(
[100002] => Array
(
[20002] => 1
)
)
)
[222] => Array
(
[1233] => Array
(
[100013] => Array
(
[20013] => 0
)
)
[1241] => Array
(
[100014] => Array
(
[20014] => 1
)
)
)
[333] => Array
(
[15633] => Array
(
[100026] => Array
(
[20026] => 0
)
)
[12144] => Array
(
[100028] => Array
(
[20028] => 0
)
)
)
)
Code to build $newarray ($stack comes from CSV with 5 columns):
$newarray = array();
foreach($stack as $val){
$lineid = $val[0]; $segmentid = $val[1]; $action = $val[2]; $recency = $val[3]; $frequency = $val[4];
$newarray[$lineid][$segmentid][$recency][$frequency] = $action;
}
Code to loop through array:
foreach($newarray as $key => $value) {
$target_pixels = array();
$owner_id = $key;
foreach($value as $key2 => $value2){
$target_pixel = new stdClass;
$target_pixel->conversion_id = $key2;
$target_pixel->negated = false;
foreach($value2 as $key3 => $value3){
$target_pixel->seconds_since_conversion = $key3 * 24 * 60 * 60;
foreach($value3 as $key4 => $value4){
$target_pixel->frequency_min = $key4;
$the_action = $value4;
}
}
$target_pixels[] = $target_pixel;
}
print_r($target_pixels);
}
Since you say you can change the structure of the array, I would go with something along the lines of:
$newarray = array();
foreach($stack as $val){
$lineid = $val[0];
$segmentid = $val[1];
$action = $val[2];
$recency = $val[3];
$frequency = $val[4];
$newarray[$lineid][$segmentid] = array(
'recency' => $recency,
'frequency' => $frequency
'action' => $action
);
}
Then your code would look like:
foreach ($newarray as $lineid => $line) {
$target_pixels = array();
$owner_id = $lineid;
foreach ($line as $segmentid => $segment){
$target_pixel = new stdClass;
$target_pixel->conversion_id = $segmentid;
$target_pixel->negated = false;
$target_pixel->seconds_since_conversion = $segment['recency'] * 24 * 60 * 60;
$target_pixel->frequency_min = $segment['frequency'];
$target_pixels[$segment['action']][] = $target_pixel;
}
var_dump($target_pixels);
}

Categories