I can't get array value using foreach - php

My problem is I get an array value from my database but when I want to show on my page using foreach it show nothing. I can't findout my problem. In the below I give my code:
controller:
$subject_code = $this->student_model->subject_code($id);
$avg = array();
foreach($subject_code as $values) {
$array_values = $values['code'];
$avg[] = $this->student_model->average($id,$array_values);
}
$data['avg'] = $avg;
view:
<td>
<?php
foreach ($avg as $avg) { ?>
<?php echo $avg['average']; ?>
<br>
<br>
<?php } ?>
</td>
The output I get when I echo $data['avg'] :
Array
(
[0] => Array
(
[0] => Array
(
[average] => 77.666667
)
)
[1] => Array
(
[0] => Array
(
[average] => 74.333333
)
)
[2] => Array
(
[0] => Array
(
[average] => 89.333333
)
)
[3] => Array
(
[0] => Array
(
[average] => 88.666667
)
)
[4] => Array
(
[0] => Array
(
[average] => 39.666667
)
)
[5] => Array
(
[0] => Array
(
[average] => 37.666667
)
)
[6] => Array
(
[0] => Array
(
[average] => 43.333333
)
)
)

Assuming you are on about foreach in your view, it looks like you are using the same variable for the key and value and you are looping over an array of arrays.
Something like this should work as long as $data['avg'] is equal to $avg
<td>
<?php foreach ($avg as $value) { ?>
<?php echo $value[0]['average']; ?>
<br>
<br>
<?php } ?>
</td>

what you are doing is creating an array for every average value and then pushing it in to the data array.
directly push it into the data array like following
$subject_code = $this->student_model->subject_code($id);
foreach($subject_code as $key=>$values) {
$array_values = $values['code'];
$data['avg'][$key] = $this->student_model->average($id,$array_values);
}
now you can use it in the foreach loop as you are already doing
<td>
<?php
foreach ($avg as $avg) { ?>
<?php echo $avg['average']; ?>
<br>
<br>
<?php } ?>
</td>

Related

Group multidimensional array by key and sum values in PHP

There are similar questions on Stack Overflow but nothing quite like mine, and I also want to double check that I am doing this the most efficient way (resource wise).
I have surveys that are submitted and I want to tally the results. Each survey is saved in a multidimensional array like so:
Array ( [name] => Clark Kent [rating] => 5 )
These are coming from a loop as they are separate database entries.
So I am beginning by creating a new array with all these combined:
$mods = array();
$index = -1;
foreach($fields as $field) {
$index++;
$mods[$index]['name'] = $field['name'];
$mods[$index]['rating'] = $field['rating'];
}
Then I am grouping these so that all the ratings for the same name are together, so I can sum them later.
$groups = array();
foreach ($mods as $value) {
$groups[$value['name']][] = $value;
}
This produces the following:
Array (
[Clark Kent] => Array (
[0] => Array (
[name] => Clark Kent
[rating] => 5
)
[1] => Array (
[name] => Clark Kent
[rating] => 5
)
)
[Peter Parker] => Array (
[0] => Array (
[name] => Peter Parker
[rating] => 5
)
[1] => Array (
[name] => Peter Parker
[rating] => 5
)
)
[Bruce Wayne] => Array (
[0] => Array (
[name] => Bruce Wayne
[rating] => 5
)
[1] => Array (
[name] => Bruce Wayne
[rating] => 5
)
)
[Bruce Banner] => Array (
[0] => Array (
[name] => Bruce Banner
[rating] => 5
)
[1] => Array (
[name] => Bruce Banner
[rating] => 5
)
)
)
What I am trying to accomplish would be something like this:
<table>
<tr>
<td>Clark Kent</td>
<td>{average of all ratings}</td>
</tr>
</table>
I'm most of the way there, but I am stuck! I'm not sure how to get the grouped name that doesn't have any type of index or key so I can use that value for my table. Then I need to sum each grouped values.
I would do all the necessary math in the loop that reads the data from the database. Something like this:
$ratings = array();
while ($row = $result->fetch_assoc()) {
$name = $row['name'];
if (!isset($ratings[$name])) {
$ratings[$name] = array('count' => 1, 'sum' => $row['rating']);
}
else {
$ratings[$name]['count']++;
$ratings[$name]['sum'] += $row['rating'];
}
}
Then you can just output your table like so:
echo "<table>";
foreach ($ratings as $name => $r) {
echo "<tr><td>$name</td><td>" . round($r['sum'] / $r['count'], 1) . "</td></tr>";
}
echo "</table>";
To get average you can do something like:
foreach ($groups as $name => $group) {
$average = array_sum(array_column($group, 'rating')) / count($group);
echo $name;
}
You could simplify the problem in the first place in the structure you are using to handle those date
foreach($fields as $field) {
$mods[$field['name']][] = $field['rating'];
}
then just foreach with the key parameter
foreach($mods as $name => $mod) {
echo $name;
echo array_sum($mod) / count($mod);
}
Try to use the code below. Eliminating an extra loop to preparing group array.
$mods = array();
foreach($fields as $field) {
$mods[$field['name']][] = $field['rating'];
}
<table>
<tr>
<?php
if($mods) {
foreach($mods as $key=>$value) {
?>
<td><?php echo $key; ?></td>
<td><?php echo (array_sum($value)/count($value)); ?></td>
<?php
}
}
?>

How to move a value up to a key, and remove a key. Array manipulation

I'm trying to change my array from this:
Array
(
[0] => Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
)
)
[1] => Array
(
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
[2] => Array
(
[BID_OPEN] => Array
(
[0] => 1.654878
)
)
)
in to this:
Array
(
[BID_OPEN]
(
[0] => 0.718282
[1] => 1.654878
)
[BID_CLOSE]
(
[0] => 1.654545
[1] => 1.645845
)
)
I'm not sure how to begin. My code:
foreach($array as $keys=>$values)
{
if(!empty($array [$c]['BID_OPEN']))
{
$inital_part1 = array("BID_OPEN", $array [$c]['BID_OPEN']);
}
else
{
echo '';
}
if(!empty($array [$c]['BID_CLOSE']))
{
$inital_part2 = array("BID_CLOSE", $array [$c]['BID_CLOSE']);
}
else
{
echo '';
}
$array1[] = $inital_part1;
$array1[] = $inital_part2;
$c++;
}
I seem to get double outputs, so the foreach when I build arrays is giving me two times the required output. Google reckons it's because I have an array in my array somewhere but I'm precisely sure I don't.
The array came from an object stdclass and I don't know what that is, have googled but haven't found anything useful. Also I'm able to get some figures but only the initial values are correct, the rest of the data doesn't seem to come through. No doubt it's because I used an index[0] to get it working.
After hours any help would be great thanks.
As long as you have told us everything about your input array it can be done quite simply like this
<?php
$in = [ ['BID_OPEN' => [0.718282]],
['BID_CLOSE' => [1.654545]],
['BID_OPEN' => [1.654878]]
];
print_r($in);
$new = []; // new array we are building
foreach ($in as $abid) {
if (array_key_exists('BID_OPEN', $abid) ) {
$new['BID_OPEN'][] = $abid['BID_OPEN'][0];
}
if (array_key_exists('BID_CLOSE', $abid) ) {
$new['BID_CLOSE'][] = $abid['BID_CLOSE'][0];
}
}
print_r($new);
THE INPUT ARRAY: Is like yours
Array
(
[0] => Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
)
)
[1] => Array
(
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
[2] => Array
(
[BID_OPEN] => Array
(
[0] => 1.654878
)
)
)
RESULT:
Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
[1] => 1.654878
)
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
$c = 0;
$array1['BID_OPEN'] = [];
$array2['BID_CLOSE'] = [];
foreach($vartttttt as $tunips=>$ert)
{
$d = 0;
foreach($ert as $erts=>$val)
{
//$array[] = $erts;
if($erts == 'BID_OPEN')
{
array_push($array1['BID_OPEN'], $val[0]);
}
if($erts == 'BID_CLOSE')
{
array_push($array2['BID_CLOSE'], $val[0]);
}
$d++;
}
$c++;
}
$array = array_merge($array1, $array2);

Multiple array values to table php

Hello how to show values in table when i have a three arrays?
I have 3 three arrays: urls,name,rok
stdClass Object
(
[urls] => Array
(
[0] => Array
(
[key] => /film/Marsjanin-2015-715533
)
[1] => Array
(
[key] => /film/Pi%C4%99%C4%87dziesi%C4%85t+twarzy+Greya-2015-655761
)
)
[name] => Array
(
[0] => Array
(
[key] => Marsjanin
)
[1] => Array
(
[key] => Pięćdziesiąt twarzy Greya
)
)
[rok] => Array
(
[0] => Array
(
[key] => (2015)
)
[1] => Array
(
[key] => (2015)
)
)
)
I want show values in table like this but missing $valu3 to third row in table, how to do?
urls name rok
/film/Marsjanin-2015-715533 Marsjanin (2015)
/film/Pi%C4%99%C4%87dziesi%C4% Pięćdziesiąt twarzy Greya (2015)
This is my code:
foreach($results as $itemz => $valuez) {
foreach($valuez as $key1 => $value1) {
foreach($value1 as $key2 => $value2) {
if ($itemz=='urls'){
$valu1[] = str_replace("/film/", "film/", $value2);
}
if($itemz=='name'){
$valu2[] = $value2;
}
if($itemz=='rok'){
$valu3[] = $value2;
}
}
}
}
$Result = array_combine($valu1, $valu2);
//echo '<pre>'; print_r($Result); echo '</pre>';
foreach($Result as $key1 => $value1) {
echo '
<tr>
<th><input type="checkbox" value="'.$key1.'" name="list[]" /></th>
<th>'.$value1.' ()</th><th>'.$rating.'</th>
<th>'.$value1.'</th>
<th>'.$genres.'</th><th>Importuj</th>
</tr>';
}
You have an object that contains three arrays with identical index number, so you can perform only one foreach loop in this way:
foreach( $results->urls as $key => $array )
{
echo $results->urls[$key]['key'];
echo $results->name[$key]['key'];
echo $results->rok[$key]['key'];
}
All the first part of code can be deleted. In the example above I simply echo values, without reproducing your html structure, because I don't understand it (you have two $value1 and a lot of <th>... ), but you can easily change it in your preferred way, like this:
echo '<td>'.$results->urls[$key]['key'].'</td>';
( etc... )

group php array by subarray value

I want to group an array by a subarray's value. If I have an array like this:
Array
(
[0] => Array
(
[userID] => 591407753
[propertyA] => 'text1'
[propertyB] => 205
)
[1] => Array
(
[userID] => 989201004
[propertyA] =>'text2'
[propertyB] => 1407
)
[2] => Array
(
[userID] => 989201004
[propertyA] => 'text3'
[propertyB] => 1407
)
)
I want to sort to group this array by a subarray's value so I can have an array like this:
Array
(
[0]=>Array
(
[userID]=>59140775
[properties]=>Array
(
[0]=>text1
)
[propertyB]=>205
)
[1]=>Array
(
[userID]=>989201004
[properties]=>Array
(
[0]=>'text2'
[1]=>'text3'
)
[propertyB]=>1047
)
)
How can I make this?
Before I had tried this:
$result = array();
foreach ($userArray as $record)
{
$id=$record['userID'];
if(isset($result[$id]))
{
$result[$id]['propertyA'][]=array($record['propertyA']);
}
else {
$record["propertyA"]=array($record['propertyA']);
unset($record['tweet']);
$result[$id]=$record;
}
}
the problem was for the propertyA. I was an the result an additional property propertyA with the table like this:
Array
(
[0]=>Array (
[userID]=>989201004
[propertyA]=>'text2'
[properties]=>Array(
[0]=>'text2'
[1]=>'text3'
)
)
)
The following code should do the job. I hope it is self-explanatory:
$result = array();
foreach ($array as $record) {
if (!isset($result[$record['userID']])) {
$result[$record['userID']] = array(
'userID' => $record['userID'],
'properties' => array($record['propertyA']),
'propertyB' => $record['propertyB'],
);
}
else {
$result[$record['userID']]['properties'][] = $record['propertyA'];
}
}
$result = array_values($result);

What I'm doing wrong in following array manipulation in foreach loop?

I've an array titled $photos as follows:
Array
(
[0] => Array
(
[fileURL] => https://www.filepicker.io/api/file/UYUkZVHERGufB0enRbJo
[filename] => IMG_0004.JPG
)
[1] => Array
(
[fileURL] => https://www.filepicker.io/api/file/WZeQAR4zRJaPyW6hDcza
[filename] => IMG_0003.JPG
)
)
Now I want to create a new array titled $values as follows :
Array
(
[vshare] => Array
(
[IMG_0003.JPG] => Array
(
[0] => https://www.filepicker.io/api/file/RqAN2jZ7ScC8eOx6ckUE
)
[IMG_0004.JPG] => Array
(
[0] => https://www.filepicker.io/api/file/XdwtFsu6RLaoZurZXPug
)
)
)
For this I tried following code :
$values = array();
foreach($photos as $photo ) {
$values['vshare'][$photo->filename] = array($photo->fileURL);
}
Then I got following wrong output when I print_r($values):
Array
(
[vshare] => Array
(
[] => Array
(
[0] =>
)
)
)
Can someone please correct the mistake I'm making in my code?
Thanks.
-> is operator for objects, as expleined in this question.
Try:
$values = array();
foreach($photos as $photo ) {
$values['vshare'][$photo['filename']] = array($photo['fileURL']);
}
<?php
$values = array();
foreach($photos as $photo ) {
$values['vshare'][$photo['filename']][0] = $photo['fileURL'];
}
you should try this code
$values = array();
foreach($photos as $photo) {
$values['vshare'][$photo['filename']] = array(0 => $photo['fileURL']);
}
Works fine for me.

Categories