PHP - array wrong output (need function help) - php

In the output of this function (at the end) you can see that the products are placed in every subArray. I want to pass through the function via an argument where the product needs to be added. The argument will be a variable on a different page: like if the variable has value "meal2" => product only needs to be added under array "meal2".
function addToMeal() {
$xmaaltijden = $_SESSION['xmaaltijden'];
$i=1;
while ( $i <= $xmaaltijden ) {
$schemas = array('maaltijd' . $i);
$i++;
$producten = $_SESSION['products'];
foreach ($schemas as $key => $schema){
foreach ($producten as $k => $product){
$variables[$schema][] = $product;
};
};
};
echo '<pre>' . print_r($variables,1) . '</pre>';
}
output:
Array
(
[meal1] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 9
)
[meal2] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 9
)
[meal3] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 9
)
)

Not:
foreach ($schemas as $key => $schema){
foreach ($producten as $k => $product){
$variables[$schema][] = $product;
};
But:
$yourVar = 'meal2';
foreach ($schemas as $key => $schema){
if ($schema === $yourVar) {
$variables[$schema] = $producten;
} else {
$variables[$schema] = array();
}
}

Related

Grouping data in ChartJS and PHP

Hi have a data table which i am trying to draw a graph of using ChartJS. The data array looks like below
Array
(
[0] => Array
(
[Sort] => 2
[Weeks] => 1-2 Weeks
[Severity] => P1
[Count] => 7
)
[1] => Array
(
[Sort] => 2
[Weeks] => 1-2 Weeks
[Severity] => P2
[Count] => 3
)
[2] => Array
(
[Sort] => 2
[Weeks] => 1-2 Weeks
[Severity] => P3
[Count] => 4
)
[3] => Array
(
[Sort] => 2
[Weeks] => 1-2 Weeks
[Severity] => P4
[Count] => 3
)
[4] => Array
(
[Sort] => 3
[Weeks] => 2-3 weeks
[Severity] => P1
[Count] => 1
)
[5] => Array
(
[Sort] => 4
[Weeks] => >4 weeks
[Severity] => No Value
[Count] => 1
)
[6] => Array
(
[Sort] => 4
[Weeks] => >4 weeks
[Severity] => P1
[Count] => 1
)
[7] => Array
(
[Sort] => 4
[Weeks] => >4 weeks
[Severity] => P3
[Count] => 1
)
)
I converted that array compatible with ChartJS like below
Array
(
[labels] => Array
(
[0] => >4 weeks
[1] => 2-3 weeks
[2] => 1-2 Weeks
)
[datasets] => Array
(
[0] => Array
(
[label] => No Value
[backgroundColor] => #F00
[borderColor] => #F00
[borderWidth] => 1
[maxBarThickness] => 50
[data] => Array
(
[0] => 1
)
)
[1] => Array
(
[label] => P1
[backgroundColor] => #84a4d4
[borderColor] => #84a4d4
[borderWidth] => 1
[maxBarThickness] => 50
[data] => Array
(
[0] => 1
[1] => 1
[2] => 7
)
)
[2] => Array
(
[label] => P3
[backgroundColor] => #eb8d22
[borderColor] => #eb8d22
[borderWidth] => 1
[maxBarThickness] => 50
[data] => Array
(
[0] => 1
[1] => 4
)
)
[3] => Array
(
[label] => P2
[backgroundColor] => #FBCEB1
[borderColor] => #FBCEB1
[borderWidth] => 1
[maxBarThickness] => 50
[data] => Array
(
[0] => 3
)
)
[4] => Array
(
[label] => P4
[backgroundColor] => #7FFFD4
[borderColor] => #7FFFD4
[borderWidth] => 1
[maxBarThickness] => 50
[data] => Array
(
[0] => 3
)
)
)
)
But the data gets scrambled when it is plotted to Chart. The data gets arranged like this
This is the real data and how the graph should look like
Here is my code
function chart(){
$ar= RNCPHP\AnalyticsReport::fetch('Open tickets Ageing by priority');
$arr= $ar->run(0, $filters);
$chartInit = array();
$chartArr['data'] = array();
// push the report data into an array
for ( $ii = $arr->count(); $ii--; ) {
$row = $arr->next();
if($row['Severity'] == null || $row['Severity'] == "") {
$row['Severity'] = "No Value";
}
$row['Sort'] = $row['Sort'];
array_push($chartInit, $row);
}
echo "<pre>";
print_r($chartInit);
array_multisort(array_map(function($element) {
return $element['Sort'];
}, $chartInit), SORT_DESC, $chartInit);
$chartDataArr = array();
$sevArr = array();
foreach($chartInit as $k => $v) {
if(!isset($chartDataArr[$v['Weeks']])) {
$chartDataArr[$v['Weeks']] = array();
}
array_push($chartDataArr[$v['Weeks']], $v);
if(!in_array($v['Severity'], $sevArr)) {
array_push($sevArr, $v['Severity']);
}
}
$mapLabels = array();
$parsedAry = array();
$parsedAry['labels'] = array();
$parsedAry['datasets'] = array();
for($i = 0; $i < count($sevArr); $i++) {
$parsedAry['datasets'][$i] = array();
$parsedAry['datasets'][$i]['label'] = $sevArr[$i];
$parsedAry['datasets'][$i]['backgroundColor'] = $this->getColor($i);
$parsedAry['datasets'][$i]['borderColor'] = $this->getColor($i);
$parsedAry['datasets'][$i]['borderWidth'] = 1;
$parsedAry['datasets'][$i]['maxBarThickness'] = 50;
$parsedAry['datasets'][$i]['data'] = array();
}
foreach($chartDataArr as $k => $v) {
array_push($parsedAry['labels'], $k);
foreach($v as $k1 => $v1) {
$keySev = "";
foreach($parsedAry['datasets'] as $k2 => $v2) {
if($v2['label'] == $v1['Severity']) {
$keySev = $k2;
}
}
if($v1['Count'] == null || $v1['Count'] == "") {
$v1['Count'] = 0;
}
array_push($parsedAry['datasets'][$keySev]['data'], $v1['Count']);
}
}
echo "<pre>";
print_r($parsedAry);
echo "</pre>";
$chartArr['data'] = $parsedAry;
return $chartArr;
}
In my view page i'm displaying data with ChartJS Function
<canvas id="chart6"></canvas>
<script>
var ctx = document.getElementById('chart6').getContext('2d');
var data = <?php echo $data ?>;
var drawChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
},
title: {
display: true,
text: 'Open tickets Ageing by priority'
}
}
});
</script>
Please Help.
Your code has several problems.
First, your datasets should has data in numbers of labels so you can't ignore empty places without filling them. To fix this problem you need to change
$parsedAry['datasets'][$i]['data'] = array(); to $parsedAry['datasets'][$i]['data'] = array(0, 0, 0, 0, 0);
This will add 5 empty spot in your datasets.
Second you have to put numbers in right places for this one you have to add a counter for your last loop to identify right places.
Finally your code should look like this.
function chart()
{
$ar = RNCPHP\AnalyticsReport::fetch('Open tickets Ageing by priority');
$arr = $ar->run(0, $filters);
$chartInit = array();
$chartArr['data'] = array();
// push the report data into an array
for ($ii = $arr->count(); $ii--;) {
$row = $arr->next();
if ($row['Severity'] == null || $row['Severity'] == "") {
$row['Severity'] = "No Value";
}
$row['Sort'] = $row['Sort'];
array_push($chartInit, $row);
}
echo "<pre>";
print_r($chartInit);
array_multisort(array_map(function ($element) {
return $element['Sort'];
}, $chartInit), SORT_DESC, $chartInit);
$chartDataArr = array();
$sevArr = array();
foreach ($chartInit as $k => $v) {
if (!isset($chartDataArr[$v['Weeks']])) {
$chartDataArr[$v['Weeks']] = array();
}
array_push($chartDataArr[$v['Weeks']], $v);
if (!in_array($v['Severity'], $sevArr)) {
array_push($sevArr, $v['Severity']);
}
}
$mapLabels = array();
$parsedAry = array();
$parsedAry['labels'] = array();
$parsedAry['datasets'] = array();
for ($i = 0; $i < count($sevArr); $i++) {
$parsedAry['datasets'][$i] = array();
$parsedAry['datasets'][$i]['label'] = $sevArr[$i];
$parsedAry['datasets'][$i]['backgroundColor'] = $this->getColor($i);
$parsedAry['datasets'][$i]['borderColor'] = $this->getColor($i);
$parsedAry['datasets'][$i]['borderWidth'] = 1;
$parsedAry['datasets'][$i]['maxBarThickness'] = 50;
$parsedAry['datasets'][$i]['data'] = array(0, 0, 0, 0, 0);
}
$labelsNo = 0;
foreach ($chartDataArr as $k => $v) {
array_push($parsedAry['labels'], $k);
foreach ($v as $k1 => $v1) {
$keySev = "";
foreach ($parsedAry['datasets'] as $k2 => $v2) {
if ($v2['label'] == $v1['Severity']) {
$keySev = $k2;
}
}
if ($v1['Count'] == null || $v1['Count'] == "") {
$v1['Count'] = 0;
}
$parsedAry['datasets'][$keySev]['data'][$labelsNo] = $v1['Count'];
}
$labelsNo++;
}
echo "<pre>";
print_r($parsedAry);
echo "</pre>";
$chartArr['data'] = $parsedAry;
return $chartArr;
}

Sort array values based on parent/child relationship

I am trying to sort an array to ensure that the parent of any item always exists before it in the array. For example:
Array
(
[0] => Array
(
[0] => 207306
[1] => Bob
[2] =>
)
[1] => Array
(
[0] => 199730
[1] => Sam
[2] => 199714
)
[2] => Array
(
[0] => 199728
[1] => Simon
[2] => 207306
)
[3] => Array
(
[0] => 199714
[1] => John
[2] => 207306
)
[4] => Array
(
[0] => 199716
[1] => Tom
[2] => 199718
)
[5] => Array
(
[0] => 199718
[1] => Phillip
[2] => 207306
)
[6] => Array
(
[0] => 199720
[1] => James
[2] => 207306
)
)
In the above array this "fails" as [1][2] (Sam) does not yet exist and nor does [4][2] (Tom).
The correct output would be as, in this case, as both Sam and Tom's parents already exist before they appear in the array:
Array
(
[0] => Array
(
[0] => 207306
[1] => Bob
[2] =>
)
[1] => Array
(
[0] => 199714
[1] => John
[2] => 207306
)
[2] => Array
(
[0] => 199730
[1] => Sam
[2] => 199714
)
[3] => Array
(
[0] => 199728
[1] => Simon
[2] => 207306
)
[4] => Array
(
[0] => 199718
[1] => Phillip
[2] => 207306
)
[5] => Array
(
[0] => 199716
[1] => Tom
[2] => 199718
)
[6] => Array
(
[0] => 199720
[1] => James
[2] => 207306
)
)
I found an answer https://stackoverflow.com/a/12961400/1278201 which was very close but it only seems to go one level deep (i.e. there is only ever one parent) whereas in my case there could be 1 or 10 levels deep in the hierarchy.
How do I sort the array so no value can appear unless its parent already exists before it?
This will trivially order the array (in O(n)) putting first all those with no parent, then these whose parent is already in the array, iteratively, until there's no children having the current element as parent.
# map the children by parent
$parents = ['' => []];
foreach ($array as $val) {
$parents[$val[2]][] = $val;
}
# start with those with no parent
$sorted = $parents[''];
# add the children the current nodes are parent of until the array is empty
foreach ($sorted as &$val) {
if (isset($parents[$val[0]])) {
foreach ($parents[$val[0]] as $next) {
$sorted[] = $next;
}
}
}
This code requires PHP 7, it may not work in some cases under PHP 5. - for PHP 5 compatibility you will have to swap the foreach ($sorted as &$val) with for ($val = reset($sorted); $val; $val = next($sorted)):
# a bit slower loop which works in all versions
for ($val = reset($sorted); $val; $val = next($sorted)) {
if (isset($parents[$val[0]])) {
foreach ($parents[$val[0]] as $next) {
$sorted[] = $next;
}
}
}
Live demo: https://3v4l.org/Uk6Gs
I have two different version for you.
a) Using a "walk the tree" approach with recursion and references to minimize memory consumption
$data = [
[207306,'Bob',''], [199730,'Sam',199714],
[199728,'Simon',207306], [199714,'John',207306],
[199716, 'Tom',199718], [199718,'Phillip',207306],
[199720,'James',207306]
];
$list = [];
generateList($data, '', $list);
var_dump($list);
function generateList($data, $id, &$list) {
foreach($data as $d) {
if($d[2] == $id) {
$list[] = $d; // Child found, add it to list
generateList($data, $d[0], $list); // Now search for childs of this child
}
}
}
b) Using phps built in uusort()function (seems only to work up to php 5.x and not with php7+)
$data = [
[207306,'Bob',''], [199730,'Sam',199714],
[199728,'Simon',207306], [199714,'John',207306],
[199716, 'Tom',199718], [199718,'Phillip',207306],
[199720,'James',207306]
];
usort($data, 'cmp');
var_dump($data);
function cmp($a, $b) {
if($a[2] == '' || $a[0] == $b[2]) return -1; //$a is root element or $b is child of $a
if($b[2] == '' || $b[0] == $a[2]) return 1; //$b is root element or $a is child of $b
return 0; // both elements have no direct relation
}
I checked this works in PHP 5.6 and PHP 7
Sample array:
$array = Array(0 => Array(
0 => 207306,
1 => 'Bob',
2 => '',
),
1 => Array
(
0 => 199730,
1 => 'Sam',
2 => 199714,
),
2 => Array
(
0 => 199728,
1 => 'Simon',
2 => 207306,
),
3 => Array
(
0 => 199714,
1 => 'John',
2 => 207306,
),
4 => Array
(
0 => 199716,
1 => 'Tom',
2 => 199718,
),
5 => Array
(
0 => 199718,
1 => 'Phillip',
2 => 207306,
),
6 => Array
(
0 => 199720,
1 => 'James',
2 => 207306,
),
);
echo "<pre>";
$emp = array();
//form the array with parent and child
foreach ($array as $val) {
$manager = ($val[2] == '') ? 0 : $val[2];
$exist = array_search_key($val[2], $emp);
if ($exist)
$emp[$exist[0]][$val[0]] = $val;
else
//print_R(array_search_key(199714,$emp));
$emp[$manager][$val[0]] = $val;
}
$u_emp = $emp[0];
unset($emp[0]);
//associate the correct child/emp after the manager
foreach ($emp as $k => $val) {
$exist = array_search_key($k, $u_emp);
$pos = array_search($k, array_keys($u_emp));
$u_emp = array_slice($u_emp, 0, $pos+1, true) +
$val +
array_slice($u_emp, $pos-1, count($u_emp) - 1, true);
}
print_R($u_emp); //print the final result
// key search function from the array
function array_search_key($needle_key, $array, $parent = array())
{
foreach ($array AS $key => $value) {
$parent = array();
if ($key == $needle_key)
return $parent;
if (is_array($value)) {
array_push($parent, $key);
if (($result = array_search_key($needle_key, $value, $parent)) !== false)
return $parent;
}
}
return false;
}
Find the below code that might be helpful.So, your output is stored in $sortedarray.
$a=array(array(207306,'Bob',''),
array (199730,'Sam',199714),
array(199728,'Simon',207306),
array(199714,'John',207306),
array(199716,'Tom',199718),
array(199718,'Phillip',207306),
array(199720,'James',207306));
$sortedarray=$a;
foreach($a as $key=>$value){
$checkvalue=$value[2];
$checkkey=$key;
foreach($a as $key2=>$value2){
if($key<$key2){
if ($value2[0]===$checkvalue){
$sortedarray[$key]=$value2;
$sortedarray[$key2]=$value;
}else{
}
}
}
}
print_r($sortedarray);
What about this approach:
Create an empty array result.
Loop over your array and only take the items out of it where [2] is empty and insert them into result.
When this Loop is done you use a foreach-Loop inside a while-loop. With the foreach-Loop you take every item out of your array where [2] is already part of result. And you do this as long as your array contains anything.
$result = array();
$result[''] = 'root';
while(!empty($yourArray)){
foreach($yourArray as $i=>$value){
if(isset($result[$value[2]])){
// use the next line only to show old order
$value['oldIndex'] = $i;
$result[$value[0]] = $value;
unset($yourArray[$i]);
}
}
}
unset($result['']);
PS: You may run into trouble by removing parts of an array while walking over it. If you do so ... try to solve this :)
PPS: Think about a break condition if your array have an unsolved loop or a child without an parent.
you can use your array in variable $arr and use this code it will give you required output.
function check($a, $b) {
return ($a[0] == $b[2]) ? -1 : 1;
}
uasort($arr, 'check');
echo '<pre>';
print_r(array_values($arr));
echo '</pre>';

Get total for value in arrays

I am trying to find a way to allow me to count the number of times a value appears across multiple arrays as well as, for each unique value, the total count.
The data looks like the below:
Array ( [id] => 4383 [score] => 3 )
Array ( [id] => 4382 [score] => 4 )
Array ( [id] => 4381 [score] => 5 )
Array ( [id] => 4383 [score] => 7 )
Array ( [id] => 4383 [score] => 1 )
Array ( [id] => 4382 [score] => 2 )
Array ( [id] => 4381 [score] => 8 )
The above should return:
4383 - 3 - 11
4382 - 2 - 6
4381 - 2 - 13
I have used array_push and created one array called $output and looped using foreach to get a count of the id's using:
foreach($output as $row) {
$array[$row[0]]++;
}
This returns the correct count of id but I cannot get the total score for each id - I have tried:
foreach($output as $row) {
foreach($row as $r) {
$array[$row[0]]=$array[$row[1]]+$array[$r[1]];
}
}
but it returns zero for everything
Like below:
$result = array();
foreach ($data as $value) {
if (!isset($result[$value['id']])) {
$result[$value['id']] = array('count' => 0, 'sum' => 0);
}
$result[$value['id']]['count'] += 1;
$result[$value['id']]['sum'] += $value['score'];
}
$result = array();
foreach ($output as $row) {
if (!array_key_exists($row[0], $result)) {
$result[$row[0]] = array("Count" => 1, "Total" => $row[1]);
}
else {
$result[$row[0]]['Count'] += 1;
$result[$row[0]]['Total'] += $row[1];
}
}
print_r($result);

How to group keys and values of an (sub)array and sum its values using PHP? [duplicate]

This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 9 months ago.
I have the following array
Array (
[0] => Array
(
[0] => ALFA
[1] => 213
)
[1] => Array
(
[0] => ALFA
[1] => 151
)
[2] => Array
(
[0] => ALFA
[1] => 197
)
[3] => Array
(
[0] => BETA
[1] => 167
)
[4] => Array
(
[0] => ZETA
[1] => 254
)
[5] => Array
(
[0] => GAMA
[1] => 138
)
[6] => Array
(
[0] => GAMA
[1] => 213
)
)
And I would like to group the key[0] of the subarray so I can see how many equal keys it has.
Something like that:
ALFA => 3
BETA => 1
EPSI => 1
GAMA => 2
I tried with array_count_values, but without success.
foreach ($array as $value) {
echo '<pre>';
print_r(array_count_values($value));
echo '</pre>';
}
With that we have following result:
Array
(
[ALFA] => 1
[213] => 1
)
Array
(
[ALFA] => 1
[151] => 1
)
...
Array
(
[GAMA] => 1
[213] => 1
)
And after that I would like to sum the values of each group as well.
ALFA => 213 + 151 + 197
BETA => 167
ZETA => 254
GAMA => 138 + 213
I think that when we solve the first part of the problem, the second would follow easier with quite the same method.
The final purpose is to divide the sum of values by the number of occurrences of each key group, so we can have an average of the values just like that:
ALFA => (213+151+197) / 3 = 187
BETA => 167
ZETA => 254
GAMA => (138+213) / 2 = 175,5
This is not the main problem, but as I said, I'm stuck with the beginning of the solution and would appreciate any help.
I'm surprised at all the long and complicated answers. However, the initial foreach to model your data to something manageable is needed. After that you just need to do a really simple array_walk.
<?php
$result = array();
foreach ($array as $el) {
if (!array_key_exists($el[0], $result)) {
$result[$el[0]] = array();
}
$result[$el[0]][] = $el[1];
}
array_walk($result, create_function('&$v,$k', '$v = array_sum($v) / count($v);'));
?>
Result:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Solution for you is here:
Code:
$input = [
['alfa', 123],
['alfa', 223],
['alfa', 122],
['alfa', 554],
['alfa', 34],
['dalfa', 123],
['halfa', 223],
['dalfa', 122],
['halfa', 554],
['ralfa', 34]
];
$result = [];
foreach ($input as $node) {
if (isset($result[$node[0]])) {
$result[$node[0]] = ['sum' => $result[$node[0]]['sum'] + $node[1], 'count' => $result[$node[0]]['count'] + 1];
} else {
$result[$node[0]] = ['sum' => $node[1], 'count' => 1];
}
}
print_r($result);
foreach ($result as $key => &$data) {
$data = $data['sum'] / $data['count'];
}
print_r($result);
Output:
Array
(
[alfa] => Array
(
[sum] => 1056
[count] => 5
)
[dalfa] => Array
(
[sum] => 245
[count] => 2
)
[halfa] => Array
(
[sum] => 777
[count] => 2
)
[ralfa] => Array
(
[sum] => 34
[count] => 1
)
)
Array
(
[alfa] => 211.2
[dalfa] => 122.5
[halfa] => 388.5
[ralfa] => 34
)
$sort = array();
foreach ($array as $value) {
$sort[$value[0]][] = $value[1];
}
then you count how many keys each has
$keys = array();
foreach($sort as $k => $v) {
$keys[$k] = count($v);
}
then for calculating the amount
$sum = array();
$average = array();
foreach($sort as $k => $v) {
$amount = 0;
foreach($v as $val) {
$amount += $val;
}
$sum[$k] = $amount;
$average[$k] = $amount / $keys[$k];
}
HOWEVER, If you want all the details in one array:
$final = array();
foreach ($array as $value) {
$final[$value[0]]["values"][] = $value[1];
}
foreach($final as $k => $v) {
$final[$k]["amount"] = count($v['values']);
$amount = 0;
foreach($v['values'] as $val) {
$amount += $val;
}
$final[$k]["sum"] = $amount;
$final[$k]["average"] = $amount / $final[$k]["amount"];
}
example: http://jdl-enterprises.co.uk/sof/25789697.php
Includes Output
Just copy the codes to your favorite text editor, sure it works perfectly.
$items = [
['ALFA',213],
['ALFA',151],
['ALFA',197],
['BETA',167],
['ZETA',254],
['GAMA',138],
['GAMA',213]
];
echo '<pre>' . print_r($items,true) . '</pre>';
$result;
foreach ($items as $value) {
# code...
if (isset($result[$value[0]])) {
$sum = $result[$value[0]]['sum'] + $value[1];
$count = $result[$value[0]]['count'] + 1;
$result[$value[0]] = ['sum' => $sum , 'count' => $count, 'divided' => ($sum / $count)];
} else {
$result[$value[0]] = ['sum' => $value[1] , 'count' => 1 , 'divided' => ($value[1] / 1) ];
}
}
echo '<pre>' . print_r($result,true) . '</pre>';
$myArray = [
["ALFA",213],
["ALFA",151],
["ALFA",197],
["BETA",167],
["ZETA",254],
["GAMA",138],
["GAMA",213]
];
$a1 = array(); //TEMPORARY ARRAY FOR KEEPING COUNT & TOTAL VALUES
$res = array(); //ARRAY USED TO KEEP RESULT
foreach($myArray as $val)
{
//AVOID PESKY NOTICES FOR UNDEFINED INDEXES
if ( !array_key_exists($val[0],$a1) ) {
$a1[$val[0]] = array("count" => 0,"total" => 0);
$res[$val[0]] = 0;
}
//INCREMENT THE COUNT OF INSTANCES OF THIS KEY
$a1[$val[0]]["count"]++;
//INCREMENT THE TOTAL VALUE OF INSTANCES OF THIS KEY
$a1[$val[0]]["total"]+=$val[1];
// UPDATE RESULT ARRAY
$res[$val[0]] = $a1[$val[0]]["total"] / $a1[$val[0]]["count"];
}
print_r($res);
Should result in:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Sample: http://phpfiddle.org/lite/code/a7nt-5svf

How to get value from multidimensional array value

Array
(
[updateCategories] => Array
(
[products] => Array
(
[0] => Array
(
[cat_id] => 3
[position] => 2
[product_id] => 8
)
[1] => Array
(
[cat_id] => 4
[position] => 11
[product_id] => 8
)
[2] => Array
(
[cat_id] => 3
[position] => 4
[product_id] => 39
)
[3] => Array
(
[cat_id] => 4
[position] => 9
[product_id] => 8
)
[4] => Array
(
[cat_id] => 3
[position] => 6
[product_id] => 41
)
[5] => Array
(
[cat_id] => 11
[position] => 7
[product_id] => 8
)
The above array is my output array but I need to get all cat_id of product_id=8. How can I do this?
$newarr = array();
foreach( $arr['updateCategories']['products'] as $myarr)
{
if($myarr['product_id'] == 8)
$newarr[] = $myarr['cat_id'];
}
The simpliest solution is
$result = array();
foreach($yourArray['updateCategories']['products'] as $product)
if($product['product_id] == 8)
$product[] = $product['cat_id'];
where $yourArray is the array which dump you have published.
Try something like this:
$arr = array();
foreach ($products as $key => $value)
{
if($value['product_id'] == 8)
{
$arr[] = $key;
}
}
print_r($arr); // <-- this should output the array of products with key as 8
Use this
foreach($array['updateCategories']['products'] as $product) {
if(isset($product['product_id']) && $product['product_id']==8) {
//do anything you want i am echoing
echo $product['cat_id'];
}
}
You can use array_filter.
function filterProducts($product) {
return ($product['product_id'] == 8);
}
$myProducts = array_filter(
$myArray['updateCategories']['products'],
'filterProducts'
);
Where $myArray is the array displayed in your post.
Can handle this by doing something like this
$matching_products = array();
foreach ($products as $key => $value) {
if($value['product_id'] == 8) {
$matching_products[] = $value['cat_id'];
}
}
which'll leave you with an array of cat ids that have a product id of 8
This should be able to retrieve all of the cat_id's from a given product_id. This function yields an object that can be iterated over to retrieve all the values it contains.
<?PHP
public function GetCatIdsByProductId($productId)
{
foreach($updateCategories=>products as $key=>$product)
{
if (isset($product=>product_id) && $product=>product_id == 8)
{
yield $product=>cat_id;
}
}
}
//Usage
$catIds = GetCatIdsByProductId(8);
var_dump($catIds);
A more generic version of this function can be constructed to retrieve a given key from a comparison on a given property value.
public function GetPropertyByPropertyComparison(array $list, $propRet, $propCompare, $compValue)
{
foreach($list as $key=>$product)
{
if (isset($product=>{$propCompare}) && $product=>{$propCompare} == $compValue)
{
yield $product=>{$propRet};
}
}
}
//usage
$cats = GetPropertyByPropertyComparison($updateCategories=>products, "cat_id", "product_id", 8);
var_dump($cats);
?>

Categories