Divide numbers in 2 multidimensional array - php

I have 2 sets of multidimensional array ($profit & $sales). I want to divide the numbers in 2 multidimensional array to get the % of margin (using this formula: $profit/$sales*100)
$profit= array(
0 => array(
"no"=> "1",
"value"=>"10"
),
1=> array(
"no"=> "2",
"value"=>"15"
)
);
$sales= array(
0 => array(
"no"=> "1",
"value"=>"100"
),
1=> array(
"no"=> "2",
"value"=>"200"
)
);
This is the expected output:
$margin= array(
0 => array(
"no"=> "1",
"value"=>"10"
),
1=> array(
"no"=> "2",
"value"=>"7.5"
)
);
I have done some search with no luck still, below is the function that I'm using, it is not working:
function ArrayDivide($arrayList = [])
{
$m = [];
$no_details = [];
$i = 0;
foreach ($arrayList as $arrayItem) {
foreach ($arrayItem as $subArray) {
if (isset($no_details[$subArray['x']])) {//if no is exist
$m[$no_details[$subArray['x']]]['y'] = $m[$no_details[$subArray['x']]]['y'] /$subArray['y']*100;
} else {
$no_details[$subArray['x']] = $i;
$m[$i] = ["x"=>$subArray['x'], "y"=>"0"];
$i++;
}
}
}
return $m;
}
How you done similar function before? Where should I fix?
Thanks.

Use "Sourcey86" code and replace:
$res = $value / $no;
to
$res = $value/$sales[$key]['value']*100;
(I don't have enough points to add a comment on his post :D )

Something like this ? If I understood your question correctly.
function getMargin($profit, $sales){
$margin = [];
foreach($profit as $key => $val){
$no = $val['no'];
$value = $val['value'];
if(isset($sales[$key]) && $sales[$key]['no'] == $no){
$res = ($value/$sales[$key]['value'])*100;
$margin[$key]['no'] = $no;
$margin[$key]['val'] = $res;
}
}
return $margin;
}
var_dump(getMargin($profit, $sales));

Related

php array: if identical key values then choose highest by other key value

$myArray = [
"ID" => "",
"Module" => "",
"Version"=> ""
];
Output:
[
{23,finance,1.0},
{24,finance,1.1},
{25,logistic,1.0}
]
I have an array with the given Keys like above. I need a new array that gives me the highest Version IF module is same. How would I do that?
desired Output:
[
{24,finance,1.1},
{25,logistic,1.0}
]
This is what I tried
$modulesFiltered = [];
$i = 0;
$j = 0;
foreach($modules as $module){
$modulesFiltered[$i]['ID'] = $module['ID'];
foreach($modulesFiltered as $moduleF){
if(!empty($moduleF[$j]['Module'])){
if($module[$i]['Module'] == $moduleF[$j]['Module']){
$modulesFiltered[$i]['Module'] = 'this is doubled';
}
} else {
$modulesFiltered[$i]['Module'] = $module['Module'];
}
$j++;
}
$modulesFiltered[$i]['Module'] = $module['Module'];
$i++;
}
I tried to debug your code though.The problem is that you try to access element [0] of $moduleF. You should change $moduleF[$j]['Module'] to $moduleF['Module'].
Use standard functions where possible. for finding values within (multidimensional) array's you can use array_search. The code beneath works.
Also don't compare strings with == use strcmp(str1, str2) == 0 instead
$inputArray = array(
array(
"ID" => 23,
"Module" => "finance",
"Version"=> 1.0),
array(
"ID" => 24,
"Module" => "finance",
"Version"=> 1.1),
array(
"ID" => 25,
"Module" => "logistiscs",
"Version"=> 1.0));
$output = array();
foreach($inputArray as $element)
{
$key = array_search($element["Module"], array_column($output, "Module"));
if(is_numeric($key))
$output[$key]["Version"] = max($element["Version"], $output[$key]["Version"]);
else
$output[] = $element;
}
print_r($output);

PHP adding values inside multidimensional array

Please find below the code sample for adding repeated values inside inner array. Can anyone suggest an alternative way to add the values faster? The code will work with smaller arrays, but I want to add big arrays that contain huge amount of data. Also I want to increase execution time.
<?php
$testArry = array();
$testArry[0] = array(
"text" => "AB",
"count" => 2
);
$testArry[1] = array(
"text" => "AB",
"count" => 5
);
$testArry[2] = array(
"text" => "BC",
"count" => 1
);
$testArry[3] = array(
"text" => "BD",
"count" => 1
);
$testArry[4] = array(
"text" => "BC",
"count" => 7
);
$testArry[5] = array(
"text" => "AB",
"count" => 6
);
$testArry[6] = array(
"text" => "AB",
"count" => 2
);
$testArry[7] = array(
"text" => "BD",
"count" => 111
);
$match_key = array();
$final = array();
foreach ($testArry as $current_key => $current_array) {
$match_key = array();
foreach ($testArry as $search_key => $search_array) {
$key = '';
if ($search_array['text'] == $current_array['text']) {
$match_key[] = $search_key;
$key = $search_array['text'];
if (isset($final[$key])) {
$final[$key] += $search_array['count'];
} else {
$final[$key] = $search_array['count'];
}
}
}
for ($j = 0; $j < count($match_key); $j++) {
unset($testArry[$match_key[$j]]);
}
}
print_r($final);
?>
Anyway to add memory during the execution time?
Thank you.
One array_walk will be enough to solve your problem,
$final = [];
array_walk($testArry, function($item) use(&$final){
$final[$item['text']] = (!empty($final[$item['text']]) ? $final[$item['text']] : 0) + $item['count'];
});
print_r($final);
Output
Array
(
[AB] => 15
[BC] => 8
[BD] => 112
)
Demo
array_walk — Apply a user supplied function to every member of an array
array_map() - Applies the callback to the elements of the given arrays
array_key_exists() - Checks if the given key or index exists in the array
You can use array_walk and array_key_exists to iterate through the array element and sum the one which has text index same
$res = [];
array_map(function($v) use (&$res){
array_key_exists($v['text'], $res) ? ($res[$v['text']] += $v['count']) : ($res[$v['text']] = $v['count']);
}, $testArry);

Create an array with dynamic input in PHP

I have to create a array dynamically like I have a method which will pass keys and based on those keys I need to create arrays inside them
Format will be like-
{
"TEST1":{
"140724":[
{
"A":"1107",
"B":4444,
"C":"1129",
"D":"1129"
},
{
"A":"1010",
"B":2589,
"C":"1040",
"D":"1040"
}
],
"140725":[
]
}
}
So how should I frame this logic inside for loop. I am new to php so formatting the same creating trouble.
$json_Created = array("TEST1" => array());
foreach($val as $key=>$value){
array_push($json_created,array($key = array()));
}
The entire array is dynamic, so like I have 140724 ,,, till 140731 (actually date format yymmdd), any amount if numbers can be considered. SO that part is dynamic moreover some dates may be wont have any values and some will have.
So my main point is to develop that logic so that irrespective the
number of inputs , my array formation must be intact.
You can use json_encode with array to do so
$array = array(
"TEST1" => array(
"140724" => array(
array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
),
array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
)
),
"140725" => array(
)
)
);
echo json_encode($array);
Another way to construct array is
$array = array();
$array["TEST1"]["140724"][] = array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
);
$array["TEST1"]["140724"][] = array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
);
$array["TEST1"]["140725"] = array();
echo json_encode($array);
Finally managed to write the code-
$keys_content = array("starttime", "id", "duration", "endtime");
$dates = array();//140724,140725,140726140727
$mainID =“TEST1”;
$arraySuperMain = array();
$arrayMain = array();
for ($j = 0; $j < count($dates); $j++) {
$array_main = array();
$subset = array();
for ($i = 0; $i < count($keys_content); $i++) {
$key = $keys_content[$i];
$subset = array_push_assoc($subset, $key, "Value".$i);
}
$array_main = array_push_assoc($array_main, $dates[$j], $subset);
array_push($arrayMain, $array_main);
}
$createdJSON = array_push_assoc($arraySuperMain, $mainID, $arrayMain);
public static function array_push_assoc($array, $key, $value) {
$array[$key] = $value;
return $array;
}

PHP multiple arrays to one associative array

How can I merge this three arrays
$name ={"Tom", "John", "David"};
$v1 = {"Tom":100, "David":200};
$v2 = {"John":500, "Tom":400};
into one multidimensional associative array in two different ways?
One way is the key order should be same as that of array "name".
$name_merged_original_order = array (
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
"John" => Array(
"v1" => "N/A",
"v2" => 500
),
"David" => Array(
"v1" => 100,
"v2" => "N/A"
)
)
Another ways is the alphabetical of array "name":
$name_merged_asc = array (
"David" => Array(
"v1" => 100,
"v2" => "N/A"
),
"John" => Array(
"v1" => "N/A",
"v2" => 200
),
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
)
The tricky part is that array "v1" and "v2" is not ordered as the key of "name." They also don't have all keys as in "name." Thanks!
It's not tested and the easiest solution:
$name_merged_original_order = array();
foreach($name as $key){
$name_merged_original_order[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_original_order[$key]['v1'] = $v1[$key];
}
else{
$name_merged_original_order[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_original_order[$key]['v2'] = $v2[$key];
}
else{
$name_merged_original_order[$key]['v2'] = 'N/A';
}
}
sort($name);
$name_merged_asc = array();
foreach($name as $key){
$name_merged_asc[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_asc[$key]['v1'] = $v1[$key];
}
else{
$name_merged_asc[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_asc[$key]['v2'] = $v2[$key];
}
else{
$name_merged_asc[$key]['v2'] = 'N/A';
}
}
As I understand you would like something like that:
$name = array("Tom", "John", "David");
$result = array();
$v1 = array("Tom" => "200", "John" => "100", "David" => "10");
$v2 = array("Tom" => "254", "David" => "156");
$vars = array("v1", "v2");
foreach($name as $n)
{
$result[$n] = array();
foreach($vars as $v)
{
if(array_key_exists($n, ${$v}))
$result[$n][$v] = ${$v}[$n];
}
}
I hope $result is what you need.
For Example, you have these arrays:
<?php
$FirstArrays = array('a', 'b', 'c', 'd');
$SecArrays = array('1', '2', '3', '4');
1)
foreach($FirstArrays as $index => $value) {
echo $FirstArrays[$index].$SecArrays[$index];
echo "<br/>";
}
or 2)
for ($index = 0 ; $index < count($FirstArrays); $index ++) {
echo $FirstArrays[$index] . $SecArrays[$index];
echo "<br/>";
}
Assume from your comments you only want items that match in all 3 arrays:
for( $i=0; $i< count($name) ; $i++){
if( !empty( $v1[ $name[$i]]) && !empty( $v2[ $name[$i]]) ){
$newArray[$name[$i]]= array( 'v1'=> $v1[ $name[$i]], 'v2'=> $v2[ $name[$i]]):
}
}
To sort:
asort($newArray);

Dynamic array key in while loop

I'm trying to get this working:
I have an array that gets "deeper" every loop. I need to add a new array to the deepest "children" key there is.
while($row = mysql_fetch_assoc($res)) {
array_push($json["children"],
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
}
So, in a loop it would be:
array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...
... and so on. Any idea on how to get the key-selector dynamic like this?
$selector = "[children][0][children][0][children]";
array_push($json$selector);
$json = array();
$x = $json['children'];
while($row = mysql_fetch_assoc($res)) {
array_push($x,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$x = $x[0]['children'];
}
print_r( $json );
Hmmm - maybe better to assign by reference:
$children =& $json["children"];
while($row = mysql_fetch_assoc($res)) {
array_push($children,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$children =& $children[0]['children'];
}
$json = array();
$rows = range('a', 'c');
foreach (array_reverse($rows) as $x) {
$json = array('id' => $x, 'name' => 'start', 'children' => array($json));
}
print_r($json);
If you want to read an array via a string path, split the string in indices, and then you can do something like this to get the value
function f($arr, $indices) {
foreach ($indices as $key) {
if (!isset($arr[$key])) {
return null;
}
$arr = $arr[$key];
}
return $arr;
}

Categories