how to parse the following php array - php

I am trying to parse the following php array, somehow I am getting the result, but I couldn't get the expected output.
Array:
Array (
[0] => Array (
[countNos] => 2
[question_id] => 1
[question] => Is Service Best?
[rating] => 4
)
[1] => Array (
[countNos] => 1
[question_id] => 2
[question] => How much you benifitted?
[rating] => 5
)
[2] => Array (
[countNos] => 1
[question_id] => 2
[question] => How much you benifitted?
[rating] => 2
)
)
Current code:
foreach ($ratings as $rating) {
if (!in_array($rating['question_id'], $ratingArr)) {
$ratingArr[$rating['question_id']]['question_id'] = $rating['question_id'];
$ratingArr[$rating['question_id']]['question'] = $rating['question'];
}
for ($i = 5; $i >= 1; $i--) {
if (!in_array($rating['rating'], $ratingArr[$rating['question_id']]['stars'])) {
if ($i == $rating['rating']) {
$ratingArr[$rating['question_id']]['stars'][$i] = $rating['countNos'];
}
}
}
}
This is the output I am getting:
Notice: Undefined index: stars in C:\xampp\htdocs\mibs\module\Survey\src\Survey\Service\SurveyService.php on line 153
Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\mibs\module\Survey\src\Survey\Service\SurveyService.php on line 153
Array (
[1] => Array (
[question_id] => 1
[question] => Is Service Best?
[stars] => Array (
[4] => 2
)
)
[2] => Array (
[question_id] => 2
[question] => How much you benifitted?
[stars] => Array (
[5] => 1
[2] => 1
)
)
)
But I am expecting the following output:
Array(
[1] => Array(
[question_id] => 1
[question] => Is Service Best?
[stars] => Array(
[5] => 0
[4] => 2
[3] => 0
[2] => 0
[1] => 0
)
)
[2] => Array(
[question_id] => 2
[question] => How much you benifitted?
[stars] => Array(
[5] => 1
[4] => 0
[3] => 0
[2] => 1
[1] => 0
)
)
)
How can I parse this array, I am always having this type of issue, whenever I am parsing, how can I overcome this.

You're never creating a stars sub-array in $ratingArr when you initialize a new entry, that's causing the two warnings. To get all the zero entries, you should initialize this to an array of 5 zeroes. Then you don't need a loop to add the stars, you can just fill in the appropriate entry directly.
And you need to use array_key_exists, not in_array, to check whether there's already an entry for $rating['question_id'] in $ratingArr.
foreach ($ratings as $rating) {
if (!array_key_exists($rating['question_id'], $ratingArr)) {
$ratingArr[$rating['question_id']]['question_id'] = $rating['question_id'];
$ratingArr[$rating['question_id']]['question'] = $rating['question'];
$ratingArr[$rating['question_id']]['stars'] = array_fill(1, 5, 0);
}
$ratingArr[$rating['question_id']]['stars'][$rating['rating']] = $rating['countNos'];
}

Loop through your array and check if you already have a subArray with the question id in the result array. If not, initialize the subArray. And then just add the rating.
Code:
<?php
$result = [];
foreach($array as $v){
if(!isset($result[$v["question_id"]])){
$result[$v["question_id"]] = [
"question_id" => $v["question_id"],
"question" => $v["question"],
"stars" => array_fill_keys(range(5, 1), 0),
];
}
$result[$v["question_id"]]["stars"][$v["rating"]] += $v["countNos"]
}
?>

Related

How To Merge/push array into one in php

code
$result = [];
foreach ($getAllAgent as $rkey => $rvalue) {
$found = -1;
for ($i = 0; $i < count($result); $i++) {
if ($result[$i]["brokerid"] == $rvalue["brokerid"]) {
$found = $i;
$result[$i]['get_agent_details'][] = $rvalue['get_agent_details']; //here to combine
break;
}
}
// if not found, create new
if ($found == -1) {
$result[] = $rvalue;
}
results
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[id] => 3
[name] => kenang
[ic] => 932132923
[phone] => 2313123
[0] => Array
(
[id] => 4
[name] => ivan
[ic] => 32992131
[phone] => 31231
)
)
)
)
I have one set of an array, and I loop it and restructure match the data based on ID. After that I will try to merge the same data into one array, I able add into one array. But it will not combine as one. The correct result should be as below.
[get_agent_details] => Array
(
[0] => Array(
[id] => 3
[name] => kenang
[ic] => 932132923
[phone] => 2313123
),
[1] => Array
(
[id] => 4
[name] => ivan
[ic] => 32992131
[phone] => 31231
)
)
Your problem is in this line:
$result[] = $rvalue;
Consider the case where you only have one item; this will result in:
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[id] => 1
[name] => Chesney Hawkes
[ic] => 932132923
[phone] => 2313123
)
)
)
But to be consistent, you need get_agent_details to be a list of items, that happens to have one entry:
Array
(
[0] => Array
(
[id] => 2
[brokerid] => 2
[agentid] => 3
[addedby] => 1
[get_agent_details] => Array
(
[0] => Array
(
[id] => 1
[name] => Chesney Hawkes
[ic] => 932132923
[phone] => 2313123
)
)
)
)
So you need to re-arrange your data, for instance by writing:
$rvalue['get_agent_details'] = [0 => $rvalue['get_agent_details']];
$result[] = $rvalue;
Then, since get_agent_details will already be a list when you encounter a second matching item, your existing code in the inner loop will do the right thing:
// Add an item to the list
$result[$i]['get_agent_details'][] = $rvalue['get_agent_details'];

PHP array - Sum value of the same key when key are number [duplicate]

This question already has answers here:
PHP Array Group by one field and Sum up two fields [duplicate]
(2 answers)
Closed 4 months ago.
My situation is similar to this thread :
Associative array, sum values of the same key
However in my case all keys are number.
I would like to reduce / combine array where key 0 is similar and make a sum of all other keys.
Here is my original array :
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 13
[4] => 0
)
[2] => Array
(
[0] => 222032
[1] => 0
[2] => 0
[4] => 15
)
[3] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
[4] => Array
(
[0] => 222032
[1] => 0
[2] => 7
[4] => 0
)
)
and here is the output i need :
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[4] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
)
The solution of other thread is not working because they use the key name and i don't know how i can adapt this to my situation.
Please if you can give me an example of working solution.
REPLY :
For now i try something like that : Take from other thread
$sum = array_reduce($data, function ($a, $b) {
if (isset($a[$b[0]])) {
$a[$b[0]]['budget'] += $b['budget'];
}
else {
$a[$b[0]] = $b;
}
return $a;
});
But this example look is only for key named budget but in my case is number and i have 3 key [1] [2] [3] how can't sum key 1,2,4 where key 0 is similar
This should work for you:
Basically I just loop through your array and check if there is already an element in $result with the key of the first element of $v. If not I initialize it with an array_pad()'ed array of 0's + the current array of the iteration of the foreach loop.
And after this I loop through each element of $v expect the first one and add it to the result array.
At the end I just reindex the result array with array_values().
<?php
foreach($arr as $v){
if(!isset($result[$v[0]]))
$result[$v[0]] = array_pad([$v[0]], count($v), 0);
$count = count($v);
for($i = 1; $i < $count; $i++)
$result[$v[0]][$i] += $v[$i];
}
$result = array_values($result);
print_r($result);
?>
output:
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[3] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[3] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[3] => 0
)
)
try this
$data = Array
(
0 => Array
(
0 => 93042,
1 => 3,
2 => 0,
4 => 0,
),
1 => Array
(
0 => 222032,
1 => 0,
2 => 13,
4 => 0,
),
2 => Array
(
0 => 222032,
1 => 0,
2 => 0,
4 => 15,
),
3 => Array
(
0 => 152963,
1 => 45,
2 => 0,
4 => 0,
),
4 => Array
(
0 => 222032,
1 => 0,
2 => 7,
4 => 0,
),
);
var_dump($data);
// grouping
$tab1 = array();
foreach ($data as $e) {
if (!isset($tab1[$e[0]])) {
$tab1[$e[0]] = array();
}
$tab1[$e[0]][] = $e;
}
//var_dump($tab1);
// summing
$tabSum = array();
foreach ($tab1 as $id => $t) {
foreach ($t as $e) {
unset($e[0]);
if (!isset($tabSum[$id])) {
$tabSum[$id] = $e;
} else {
foreach ($e as $key => $value) {
$tabSum[$id][$key] += $value;
}
}
}
}
var_dump($tabSum);

Update quantity session array

I need a help
This is my session array:
Array
(
[menu] =>
[id] => 3
[products] => Array
(
[0] => Array
(
[id] => 1
[name] => Produkt 1
[code] => 1
[varianta] =>
[pocet] => 1
[price] => 20
[pricepredtym] => 40
)
[1] => Array
(
[id] => 2
[name] => Produkt 1
[code] => 1
[varianta] =>
[pocet] => 1
[price] => 20
[pricepredtym] => 40
)
)
)
I would need about something like, if ($_GET [id] == $ _SESSION ['products'] [id]) and only change this "[pocet]" where [id] = 2
$_GET [id] = 2;
$pocet=5;
[1] => Array
(
[id] => 2
[name] => Produkt 1
[code] => 1
[varianta] =>
[pocet] => 5
[price] => 20
[pricepredtym] => 40
)
You could index your products array by product id. Then updating would be simply:
if(isset($_SESSION['products'][$prod_id])) {
$_SESSION['products'][$prod_id]['pocet'] = $pocet;
}
Otherwise, use a foreach loop:
foreach ($_SESSION['products'] as $i => $prod) {
if ($prod['id'] == $prod_id) {
$_SESSION['products'][$i]['pocet'] = $pocet;
break;
}
}
Compare your GET value with 2 and use it as key of SESSION array.
if ($_GET['id'] == '2'){
$_SESSION['products'][$_GET['id']]['pocet'] = '5';
}

How to move an array into another? [duplicate]

This question already has answers here:
create array tree from array list [duplicate]
(9 answers)
Closed 9 years ago.
I have a multidimensional associative array "$nav_menus" looks like this:
Array
(
[0] => Array
(
[id] => 1
[menu_name] => Media
[parent_id] => 0
[submenus] => 1
)
[1] => Array
(
[id] => 2
[menu_name] => Movies
[parent_id] => 1
[submenus] => 1
)
[2] => Array
(
[id] => 3
[menu_name] => English Movies
[parent_id] => 2
[submenus] => 1
)
[3] => Array
(
[id] => 4
[menu_name] => Action
[parent_id] => 3
[submenus] => 1
)
)
What I'm trying to accomplish is to loop the array and whenever the value of the key ['parent_id'] doesn't equal 0 is to loop the array again and move this one into whatever menu the value of its ['id'] key equal that parent_id ... here is what I want $nav_menus to look like at the end
Array
(
[id] => 1
[menu_name] => Media
[parent_id] => 0
[submenus] => 1
[0] => Array
(
[id] => 2
[menu_name] => Movies
[parent_id] => 1
[submenus] => 1
[0] => Array
(
[id] => 3
[menu_name] =>English Movies
[parent_id] => 2
[submenus] => 1
[0] => Array
(
[id] => 4
[menu_name] => Action
[parent_id] => 3
[submenus] => 1
)
)
)
)
Here is what I was tried to accomplish it, but with no luck:
foreach($nav_menus as $k => $v){
if($v['parent_id'] !== 0){
$x = $v;
foreach($nav_menus as $key => $value){
if($value['id'] == $v['parent_id']){
unset($v);
array_push($value, $x);
break;
}
}
}
}
print_r($nav_menus);
It gives me the same original array without any change :( ... Any suggestions ?
Try this recursive function.
function array_new($arr1,$tot_count,$parent=0,$new_arr=array(),$global_count=0)
{
$count=0;
foreach($arr1 as $arr_res)
{
if($arr_res['parent_id']==$parent)
{
$new_arr['id'] = $arr_res['id'];
$new_arr['menu_name'] = $arr_res['menu_name'];
$new_arr['parent_id'] = $arr_res['parent_id'];
$new_arr['submenus'] = $arr_res['submenus'];
//DebugBreak();
if($global_count<$tot_count-1)
{ $global_count++;
$new_arr[$count] = array_new($arr1,$tot_count,$arr_res['id'],$new_arr,$global_count);
$count++;
}
}
}
return $new_arr;
}
'$arr_unformated' is your array which you have now.
$tot_count = count($arr_unformated);
$arrnew = array_new($arr_unformated,$tot_count);
And '$arrnew' is your desire array.

add data from 1 array to the other

after looking through loads of questions on here i still carnt find an answer that suits my situation.
im trying to join 2 fields from array #2 into array #1
Array #1
Array
(
[0] => Array
(
[id] => 1
[position] => top_banner_1
[name] => Top Banner 1
[order] => 1
)
[1] => Array
(
[id] => 2
[position] => left_banner_1
[name] => Left Banner 1
[order] => 2
)
)
Array #2
Array
(
[status] => 0
[countries] =>
[module_status] => 1
[top_banner_1_status] => 1
[top_banner_1_display] => 0
[left_banner_1_status] => 1
[left_banner_1_display] => 0
[left_banner_2_status] => 1
[left_banner_2_display] => 0
[left_banner_3_status] => 1
[left_banner_3_display] => 0
[left_banner_4_status] =>
[left_banner_4_display] => 0
[left_banner_5_status] =>
[left_banner_5_display] => 0
[center_banner_1_status] =>
[center_banner_1_display] => 0
[center_banner_2_status] =>
[center_banner_2_display] => 0
[right_banner_1_status] =>
[right_banner_1_display] => 0
[right_banner_2_status] =>
[right_banner_2_display] => 0
[right_banner_3_status] =>
[right_banner_3_display] => 0
[right_banner_4_status] =>
[right_banner_4_display] => 0
[right_banner_5_status] =>
[right_banner_5_display] => 0
[bottom_banner_1_status] =>
[bottom_banner_1_display] => 0
)
what i am trying to achive is:
Array
(
[0] => Array
(
[id] => 1
[position] => top_banner_1
[name] => Top Banner 1
[order] => 1
[top_banner_1_status] => 1
[top_banner_1_display] => 0
)
)
both of these arrays are comming from a database. there are 13 areas in array #1 so everything ive done so far is with foreach loops as array #2 data is fetched from a function that ideally i can't edit.
i've tried quite a few array_* functions but i'm not getting very far fast.
Assuming the following reasoning:
Array
(
[0] => Array
(
[id] => 1
[position] => top_banner_1
[name] => Top Banner 1
[order] => 1
[top_banner_1_status] => 1 // Added because of key is [position]_status.
[top_banner_1_display] => 0 // Added because of key is [position]_display.
)
)
I would do:
<?php
$array1 = // Array #1 from question.
$array2 = // Array #2 from question.
foreach ($array1 as $key => $item) {
$position = $item['position'];
$keySuffixes = array('_status', '_display');
foreach ($keySuffixes as $suff) {
if (array_key_exists($position . $suff, $array2)) {
$array1[$key][$position . $suff] = $array2[$position . $suff];
}
}
}
?>
Not elegant, I know :(
The trick is to construct a key according to ID to fetch data from $arr2.
foreach($arr1 as $key=>$val){
$id = $val['id'];
$tb_status_key = "top_banner_{$id}_status";
$tb_display_key = "top_banner_{$id}_display";
$arr1[$key][$tb_status_key] = $arr2[$tb_status_key];
$arr1[$key][$tb_display_key] = $arr2[$tb_display_key];
}
The structure of Array #2 is not quite apprpriate for this task. If you have the possibility, you should change it to smething like this:
Array
(
[top_banner_1] => Array (
[status] => 1
[display] => 0
)
[left_banner_1] => Array (
[status] => 1
[display] => 0
)
)
//and so on
But if this is not possible, this should work:
foreach($array1 as &$info) {
$status = $info['position'] . '_status';
$display = $info['position'] . '_display';
$info[$status] = $array2[$status];
$info[$display] = $array2[$display];
}
Otherwise, this seems to be a more elegant way:
foreach($array1 as &$info) {
$info['status'] = $array2[$info['position']]['status'];
$info['display'] = $array2[$info['position']]['display'];
}

Categories