add items to multidimensional array programmatically in php - php

I have the following array
$a = array(0 => 'Item',
1 => 'Wattles',
2 => 'Types',
3 => 'Compost',
4=> 'Estimated',
5 => '123',
6 => 'Actual',
7 => '12',
);
That is sorted with the following code.
echo "<pre>";
print_r($a);
$a_len = count($a);
$fnl = array();
$i = 0;
while($i<$a_len){
$fnl[$a[$i]] = $a[++$i];
$i++;
}
print_r($fnl);
It prints correctly
Array
(
[Item] => Wattles
[Types] => Compost
[Estimated Qty] => 123
[Actual Qty] => 12
)
until i add multiple entries.
Array
(
[0] => Item
[1] => Wattles
[2] => Types
[3] => Compost
[4] => Estimated Qty
[5] => 123
[6] => Actual Qty
[7] => 12
[8] => Item
[9] => Silt Fence
[10] => Types
[11] => Straw
[12] => Estimated Qty
[13] => 45
[14] => Actual Qty
[15] => 142
)
I need to make this add items in a multidimensional array.
$items = array
(
array("Wattles","Silt Fence), //items
array("Compost","Straw"), //types
array(123,45), //estimated quantity
array(12,142) //actual quantity
);
There are a few given numbers. There are exactly 4 entries (8 items) before the list repeats itself.
I have been stuck on this portion for hours, and don't know how to get my code working as I want it to.

To get the expected result with string keys you can do:
foreach(array_chunk($a, 2) as $pairs) {
$result[$pairs[0]][] = $pairs[1];
}
Yields:
Array
(
[Item] => Array
(
[0] => Wattles
[1] => Silt Fence
)
[Types] => Array
(
[0] => Compost
[1] => Straw
)
[Estimated] => Array
(
[0] => 123
[1] => 45
)
[Actual] => Array
(
[0] => 12
[1] => 142
)
)
Then if you want it numerically indexed:
$result = array_values($result);

You have your structure for a multidimensional array wrong. You should construct your array like this:
$a = array(
0 => array(
'Item' => 'Wattles',
'Types' => 'Compost',
'Estimated' => 123,
'Actual' => 12
)
);
Then to add to it:
$a[] = array(
'Item' => 'Silt Fence',
'Types' => 'Straw',
'Estimated' => 45,
'Actual' => 142
);
Render it out to see the results which are what I think you are looking for.
print_r($a);
I can post a link if you want to learn how to sort multidimensional arrays by sub-array values if you need.

Related

get the sum value of specific key in given array and add row of count after specific completed index

Actual I get
Array
(
[0] => Array
(
[name] => person1
[value] => 11
)
[1] => Array
(
[name] => person2
[value] => 5
)
[2] => Array
(
[name] => person2
[value] => 5
)
[3] => Array
(
[name] => person4
[value] => 10
)
)
Actually i need
Array
(
[0] => Array
(
[name] => person1
[value] => 11
)
//here i want new row index 1 array
[1] => Array
(
[name] => total
[value] => 11 //this value is the sum of index 1
)
[2] => Array
(
[name] => person2
[value] => 5
)
[3] => Array
(
[name] => person2
[value] => 5
)
// here i want add new line index 4 array
[4] => Array
(
[name] => total
[value] => 10 //this value is the sum of index 2 and 3
)
[5] => Array
(
[name] => person4
[value] => 10
)
// here i want add new line index 6 array
[6] => Array
(
[name] => total
[value] => 10 //this value is the sum of index 5
)
)
may this help you i have tried some step making grouping but sum is not correct but code may help you
$a = Array
(
0 => Array
(
'name' => 'person1',
'value' => 11,
),
1 => Array
(
'name' => 'person2',
'value' => 5,
),
2 => Array
(
'name' => 'person2',
'value' => 5,
),
3 => Array
(
'name' => 'person4',
'value' => 10,
)
);
foreach($a as $c){
$d[]=$c['name'];
$e[]=$c['value'];
}
//print_r($d);
$group = array();
foreach($d as $key=>$val){
$group[$val][] = $e[$key];
}
// this loop for check the max number and count total price
$data = array();
$total = 0;
foreach($group as $key=>$val){
for($i=0;$i<count($val);$i++){
$data[]['name'] = $key;
$data[]['value'] = $val[$i];
$suma[] = $val[$i];
}
$sunmb =array_sum($suma);
$data[]['name'] = 'total';
$data[]['value'] = $sunmb;
}
print_r($data);
You can check code run here https://wtools.io/php-sandbox/b1LD

Find maximum value in PHP array

Below is my array:
Array
(
[3] => Array
(
[2] => 3
[4] => 1
[5] => 2
[6] => 2
)
[5] => Array
(
[2] => 1
[3] => 2
[4] => 3
[6] => 3
)
In this array I want to find the maximum number and if the array contains the same maximum values then we choose one maximum value randomly.
Expected output like below:
Array
(
[3] => Array
(
[2] => 3
)
[5] => Array
(
[4] => 3
)
[6] => Array
(
[2] => 3
)
)
This is what I've tried:
$found = Array( [3] => Array ( [2] => 3 [4] => 1 [5] => 2 [6] => 2 ) [5] => Array ( [2] => 1 [3] => 2 [4] => 3 [6] => 3 ) [6] => Array ( [2] => 3 [3] => 2 [4] => 2 [5] => 3 ))
$fmaxnum = array();
foreach($found as $fk => $fv){
$fmaxnum[$fk] = max($fv);
}
echo "<pre>";print_r($fmaxnum);echo "</pre>"
You will get max value with max() but for index you have to use array_keys()
You can try this:
$found = Array ( '3' => Array ( '2' => 3 ,'4' => 1, '5' => 2, '6' => 2 ),
'5' => Array ( '2' => 1 ,'3' => 2, '4' => 3, '6' => 3 ),
'6' => Array ( '2' => 3 ,'3' => 2, '4' => 2, '5' => 3 )
);
$fmaxnum = array();
foreach($found as $fk => $fv){
$max_key = array_keys($fv, max($fv));
$fmaxnum[$fk] = array(
($max_key[0]) => max($fv) /* This will give small index value */
/* (count($max_key)-1) => => max($fv) // this will give highest index value */
);
}
echo "<pre>";
print_r($fmaxnum);
echo "</pre>";
Simple solution with array_map and array_keys functions:
// supposing $arr is your initial array
$arrMax = array_map(function($v){
$maximum = max($v);
return [array_keys($v, $maximum)[0] => $maximum];
}, $arr);
print_r($arrMax);
The output:
Array
(
[3] => Array
(
[2] => 3
)
[5] => Array
(
[4] => 3
)
[6] => Array
(
[2] => 3
)
)
if you just want to know the highest value as I understood
In this array I want to find the maximum number and if the array
contains the same maximum values then we choose one maximum value
randomly.
you could just do this
$array = [['3','1','2','2'],['1','2','3','3'],['2','1','1','3']];
$result = [];
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
$result[] = $value;
}
echo max($result);
this will foreach all the array and push the values on $result, then you just have one level array and easily use max function

Php replace array keys with another array keys if key exists

I have this array :
Array (amounts)
(
[0] => Array
(
[0] => 95
[1] => 2
)
[1] => Array
(
[0] => 96
[1] => 5
)
)
And this
Array (invoices)
(
[1] =>
[2] => 490
[3] =>
[4] =>
[5] => 1400
)
This is what I am trying to get :
Array
(
[1] =>
[95] => 490 // Id found in Amounts array so replaced id by Key '0'
[3] =>
[4] =>
[96] => 1400 // Id found in Amounts array so replaced id by Key '0'
)
I have tried to deal with the answser found here but without success.
$newamounts = array_combine(array_map(function($key) use ($invoices) {
return $invoices[$key]; // translate key to name
}, array_keys($invoices)), $amounts);
Any help greatly appreciated. Thx
This should work for you:
(Here i go through each innerArray of $amounts with a foreach loop and then i check if the array element in $invoices with the index 1 of the innerArray is not empty and if not i set the new element with the key and value and unset the old one)
<?php
$amounts = array(
array(
95,
2
),
array(
96,
5
)
);
$invoices = array(1 =>"", 2 => 490, 3 => "", 4 => "", 5 => 1500);
foreach($amounts as $innerArray) {
if(!empty($invoices[$innerArray[1]])) {
$invoices[$innerArray[0]] = $invoices[$innerArray[1]];
unset($invoices[$innerArray[1]]);
}
}
print_r($invoices);
?>
Output:
Array ( [1] => [3] => [4] => [95] => 490 [96] => 1500 )

Compare multidimensional arrays for different entries and storing them

I'm trying to teach myself how multidimensional arrays work and how I can compare and manipulate them in php I have created two arrays with the same scheme but with one different value in each.
first array
$datastuff1 = array( array( Ttitle => "rose",
Price => 1.25,
Number => 15
),
array( Ttitle => "daisy",
Price => 0.75,
Number => 25
),
array( Ttitle => "lilly",
Price => 1.75,
Number => 3
),
array( Ttitle => "orchid",
Price => 1.15,
Number => 7
)
);
second array
$datastuff2 = array( array( Title => "rose",
Price => 1.25,
Number => 15
),
array( Title => "daisy",
Price => 0.75,
Number => 25
),
array( Title => "nettle",
Price => 2.75,
Number => 33
),
array( Title => "orchid",
Price => 1.15,
Number => 7
)
);
I now want to loop through both arrays and foreach item that matches (using the title as a key) in both arrays add to a new matching array and for each item that doesn't match in both arrays add to my not matching array
heres my code
$matchingarray = array();
$notmatchingarray = array();
foreach($datastuff1 as $data1){
foreach($datastuff2 as $data2){
if($data2['Title']== $data1['Ttitle'])
{
$matchingarray[] = $data1;
}
else {
$notmatchingarray[] = $data1;
}
}
}
but when I output the contents of the arrays using
echo "<pre>";
print_r($notmatchingarray);
echo "</pre>";
I get the output
Array
(
[0] => Array
(
[Ttitle] => rose
[Price] => 1.25
[Number] => 15
)
[1] => Array
(
[Ttitle] => rose
[Price] => 1.25
[Number] => 15
)
[2] => Array
(
[Ttitle] => rose
[Price] => 1.25
[Number] => 15
)
[3] => Array
(
[Ttitle] => daisy
[Price] => 0.75
[Number] => 25
)
[4] => Array
(
[Ttitle] => daisy
[Price] => 0.75
[Number] => 25
)
[5] => Array
(
[Ttitle] => daisy
[Price] => 0.75
[Number] => 25
)
[6] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[7] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[8] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[9] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[10] => Array
(
[Ttitle] => orchid
[Price] => 1.15
[Number] => 7
)
[11] => Array
(
[Ttitle] => orchid
[Price] => 1.15
[Number] => 7
)
[12] => Array
(
[Ttitle] => orchid
[Price] => 1.15
[Number] => 7
)
)
so to me it seems as though its looping round three times (the amount of items that match) and each time putting the matching items in the array.
What I want is all the items that DON'T match (using the Title as a key) in the non-matching array and the ones that DO in the matching array. I'm missing something painstakingly obvious I suppose.
Any help would be grand
regard mike
I couldn't simply copy/paste your array definitions so I didn't test, but you need to check for equality and if found then break out of the inner loop. Also, after the inner loop, check if it was added to $matchingarray and if not, add to $notmatchingarray:
foreach($datastuff1 as $key => $data1){
foreach($datastuff2 as $data2){
//match add to $matchingarray
if($data2['Title'] == $data1['Ttitle']) {
$matchingarray[$key] = $data1; //use $key so we can check later
break; //we have a match so why keep looping?
}
}
//if no match add to $notmatchingarray
if(!isset($matchingarray[$key])) { //we used $key so we can check for it
$notmatchingarray[$key] = $data1; //don't need $key here but oh well
}
}
Alternate way that may be easier to follow:
foreach($datastuff1 as $key => $data1){
$match = false; //no match
foreach($datastuff2 as $data2) {
//match add to $matchingarray
if($data2['Title'] == $data1['Ttitle']) {
$matchingarray[] = $data1;
$match = true; //match
break; //we have a match so why keep looping?
}
}
//if no match add to $notmatchingarray
if(!$match) {
$notmatchingarray[] = $data1;
}
}

I've spent hours trying to get these array keys into variables but everything I try is not working

I have an array of all possible combinations of values, a bit like working out what monetary values I could make with only certain coins. Now I have an array built but much of the useful data are keys and not values.
A small snippet is below:
Each root key is an array with keys total, denomination and quantity. Each of the quantities multiplied by the denominations total the total. While I've been able to access the total easily enough I just can't get a handle on the denominations and the quantities.
It's my plan to output to separate radio buttons like so:
foreach($array as $arr)
{
echo '<input type="radio" name="name" value="'.$arr[$total].'">';
foreach($arr[denom] as $index => $d)
{
echo $d[qty][$index].' x '.$d[denom][$index].' = '.($qty[$index]*$denom[$index]).'<br>';
}
}
Here's the array I have, any help would be much appreciate, I'm usually great at this bot it's driving me crazy
Array
(
[2] => Array
(
[total] => 105
[denom] => Array
(
[0] => 105
)
[qty] => Array
(
[0] => 1
)
)
[3] => Array
(
[total] => 210
[denom] => Array
(
[0] => 105
)
[qty] => Array
(
[0] => 2
)
)
[4] => Array
(
[total] => 300
[denom] => Array
(
[0] => 300
)
[qty] => Array
(
[0] => 1
)
)
[5] => Array
(
[total] => 405
[denom] => Array
(
[0] => 300
[1] => 105
)
[qty] => Array
(
[0] => 1
[1] => 1
)
)
[6] => Array
(
[total] => 500
[denom] => Array
(
[0] => 500
)
[qty] => Array
(
[0] => 1
)
)
[7] => Array
(
[total] => 605
[denom] => Array
(
[0] => 500
[1] => 105
)
[qty] => Array
(
[0] => 1
[1] => 1
)
)
Constant non-numeric array indices should be written like any other string, i.e. encapsulated in quotes.
foreach($array as $arr) {
echo '<input type="radio" name="name" value="'.$arr['total'].'">';
foreach($arr['denom'] as $index => $d){
for ($j = 0;$j < count($denom);$j++) {
echo $d['qty'][$j].' x '.$d['denom'][$j].' = ';
echo ($d['qty'][$j]*$d['denom'][$j]) . '<br>';
}
}
}
First format your array like this in my code, add 6, 7 array elements. I modify for loop too.
<?php
$array = array(2 => array('total' => 105, 'denom' => array(0 => 105), 'qty' => array(0 => 1)),
3 => array('total' => 210, 'denom' => array(0 => 105), 'qty' => array(0 => 2)),
4 => array('total' => 300, 'denom' => array(0 => 300), 'qty' => array(0 => 1)),
5 => array('total' => 405, 'denom' => array(0 => 300, 1 => 105), 'qty' => array(0 => 1, 1 => 1)),
);
foreach($array as $arr)
{
//var_dump($arr);
echo '<input type="radio" name="name" value="'.$arr['total'].'">';
foreach($arr['denom'] as $index => $d)
{
echo $arr['qty'][$index].' x '.$d.' = '.($arr['qty'][$index]*$d).'<br>';
}
}
?>

Categories