Array group in php - php

I have the following array data:
[0] => stdClass Object
(
[schoolBin] => 110140014570
[schoolName] => школа-лицей № 66
[users] => 30
[tb0306_tb0301_id] => 514725
[tb0306_tb3002_id] => 17
[tb0306_countOfCorrectAnswers] => 14
[point] => 4
)
[1] => stdClass Object
(
[schoolBin] => 110140014570
[schoolName] => школа-лицей № 66
[users] => 30
[tb0306_tb0301_id] => 514725
[tb0306_tb3002_id] => 18
[tb0306_countOfCorrectAnswers] => 11
[point] => 4
)
So, i have many tb0306_tb0301_id from one schoolBin, and tb0306_tb0301_id has many tb0306_countOfCorrectAnswers of tb0306_tb3002_id. So i need to sum all tb0306_countOfCorrectAnswers of for all tb0306_tb0301_id of one schoolBin and i have many schoolBin, so i need to do the process for all schoolBin.
Tried the code:
$results = array();
foreach ($schoolResults as $schoolResult) {
$schoolBin = $schoolResult->schoolBin;
if (isset($results[$schoolBin])) {
$results[$schoolBin][] = $schoolResult;
} else {
$results[$schoolBin] = array($schoolResult);
}
}
But could not sum tb0306_countOfCorrectAnswers for one tb0306_tb0301_id.
Any helps guys!

here is the code to sum the tb0306_countOfCorrectAnswers for tb0306_tb0301_id of schoolBin. I use # to ingnore the worning for uninitial value.
$results = array();
foreach ($schoolResults as $schoolResult) {
#$result[$schoolResult->schoolBin][$schoolResult->tb0306_tb0301_id] += $schoolResult->tb0306_countOfCorrectAnswers
}

Related

Face problem during get unique value from foreach loop

I have faced a problem during get unique value in foreach loop.
Following is my array.
Array
(
[20] => Array
(
[0] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[1] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[2] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[3] => Array
(
[id] => 6
[category_title] => Cater Foil Rolls
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:24
)
)
[21] => Array
(
[8] => Array
(
[id] => 24
[category_title] => Specialist Range
[parent] => 21
[front_active] => 1
[category_date] => 2019-05-21 04:07:59
)
[9] => Array
(
[id] => 24
[category_title] => Specialist Range
[parent] => 21
[front_active] => 1
[category_date] => 2019-05-21 04:07:59
)
)
)
I written following script for getting unique value in loop
$catArray = array();
foreach($catagory_list as $key=>$catagory){
$catArray[$catagory['parent']][$key] = $catagory;
}
ksort($catArray, SORT_NUMERIC);
foreach ($catArray as $key => $value) {
if($key == 20 ){
$catName ='local';
}elseif ($key == 21) {
$catName ='interstate';
}elseif ($key == 22) {
$catName ='wholesale';
}elseif ($key == 23) {
$catName ='tst';
}
//echo $key;
foreach(array_unique($value) as $keys => $valuess){
echo $valuess['category_title'];
?>
<tr class="table_header">
<th><?php echo $catName." - ".$valuess['category_title'];?> </th>
</tr>
<?php
}
}
Problem is 20 has 4 category_title but when i used array_unique Cater Foil Rolls category title of first parent array is not display.
Output only display
Specialist Range not showing (Cater Foil Rolls)
If you are trying to find unique records in this nested array, then I would key your associative array off of the value of "id". If you are only trying to find unique category_title, then I would key off the value of "category_title". In any case I would use the associate array functionality to ensure uniqueness on whatever key you choose. Then you can apply sorting, etc. on the result.
// find first unique records
$result = [];
foreach($parents as $key1=>$child1) {
foreach($child1 as $key2=>$child2) {
if(!isset($result[$child2['id']])) {
$result[$child2['id']] = $child2;
}
}
}
// result = # => record
OR:
// find first unique categories
$result = [];
foreach($parents as $key1=>$child1) {
foreach($child1 as $key2=>$child2) {
if(!isset($result[$child2['category_title']])) {
$result[$child2['category_title']] = $child2;
}
}
}
// result = category => record
I'm not convinced that array_unique works on multi-dimensional arrays.
See this question.

PHP - Array does not turn into two-dimensional array

I need to make my array better.
I am getting data from database and i have milestones and milestone_parts. i want two-dimensional array. I need data of milestones in the first dimension and milestone_parts in the second dimension.
With this code:
$query = "
SELECT
a.id AS `milestone_id`,
a.titel AS `milestone_titel`,
a.client AS `client`,
a.verkocht_id AS `milestone_verkocht_id`,
b.id AS `milestonefase_id`,
b.titel AS `milestonefase_titel`,
b.milestone_id AS `milestonefase_milestone_id`,
b.omschrijving AS `milestonefase_omschrijving`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '99'
";
$result= $db->query($dbh, $query);
while ($row = $db->fetchassoc($result))
{
$stone = array($row['milestone_verkocht_id'], $row['milestone_id'], $row['milestone_titel'], $row['client']);
$fase = array($row['milestonefase_milestone_id'],$row['milestonefase_id'],$row['milestonefase_titel']);
$stone[] = $fase;
echo '<pre>'; print_r($stone); echo '</pre>';
}
I get this as result
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 10
[2] => string
)
)
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 11
[2] => string
)
)
but I need (with names) this:
Array
(
[milestone_verkocht_id] => 99 // This is project id
[milestone_id] => 6
[milestone_title] => string
[client] => string
[10] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 10
[milestone_title] => string
)
[11] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 11
[milestone_title] => string
)
[12] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 12
[milestone_title] => string
)
)
Can you help me or do you have a solution? Help me please!
you can cycle each field returned by the query, checking the field name and making new arrays
$stones = array();
while ($row = $db->fetchassoc($result)) {
$fase = array();
$stone = array('milestones' => array());
foreach ($row as $k => $v) {
if (strpos($k, 'milestonefase_') === 0) {
$fase[$k] = $v;
} else {
$stone[$k] = $v;
}
}
if(!isset($stones[$stone['milestone_id']])) {
$stones[$stone['milestone_id']] = $stone;
}
$stones[$stone['milestone_id']]['milestones'][$fase['milestonefase_id']] = $fase;
}
echo '<pre>'.print_r($stones, true).'</pre>';
Edit
made some changes in order to match the request. Now we use $stones to store the information we already have on a milestone, adding to it the different "$fase" returned from the query
Probably a more clean way is to retrieve all the information with two different queries one for milestones and the other for the fases
Edit2
Added a sub-array for the milestone fases

How to remove duplicate entries from associative array in php

My array is
Array
(
[0] => Array
(
[id] => 20
[new_id] => 958
[affiliate_id] => 33
)
[1] => Array
(
[id] => 21
[new_id] => 959
[affiliate_id] => 45
)
[2] => Array
(
[id] => 22
[new_id] => 960
[affiliate_id] => 23
)
[3] => Array
(
[id] => 23
[new_id] => 961
[affiliate_id] => 33
)
)
and i want array
Array
(
[0] => Array
(
[id] => 20
[new_id] => 958
[affiliate_id] => 33
)
[1] => Array
(
[id] => 21
[new_id] => 959
[affiliate_id] => 45
)
[2] => Array
(
[id] => 22
[new_id] => 960
[affiliate_id] => 23
)
)
I want to remove duplicates value of affiliate_id . According to first array i am getting affiliate_id's value is 33 for two time. But i want it for one time. So in my second array (which will be my answer) i remove it.
Try something like this, not so pretty as array_ one liners, but still:
$existing_aff_ids = array();
$unique = array();
foreach ($affiliate as $aff) {
if (!isset($existing_aff_ids[$aff['affiliate_id']])) {
$unique[] = $aff;
$existing_aff_ids[$aff['affiliate_id']] = 1;
}
}
Given $affiliates as in your answer, looping over the array and checking for affiliate_id would do the trick
$unique_affiliates = array();
foreach($affiliates as $affiliate) {
$affiliate_key = $affiliate['key'];
/* Variant 1 */
$unique_affiliates[$affiliate_key] = $affiliate;
/* Variant 2 */
if(!isset($unique_affiliates[$affiliate_key])) {
$unique_affiliates[$affiliate_key] = $affiliate;
}
}
All entries in $unique_affiliates will have unique affiliate_keys. Variant 1 will contain the last occurrence of each afffiliate_key (as in your example), whereas variant 2 will add the first occurrence of any affiliate_key and just ignore all subsequent ones.
These are not duplicate values :
1. $input = array_map("unserialize",
array_unique(array_map("serialize", $data))
2. array_values(array_unique($data))
Both this case fails because of the unique id values are there it requires all values to be same to consider it as duplicate.
Solution:Will making the array check the value of the corresponding field.
foreach($data as $key=>$val)
{
if (is_array($val))
{
$val2 = arrayUnique($val);
}
else
{
$val2 = $val;
$newArray=array_unique($data);
$newArray=deleteEmpty($newArray);
break;
}
if (!empty($val2))
{
$newArray[$key] = $val2;
}
}
print_r($newArray);

Adding Elements To An StdClass Array - PHP / Codeigniter

I have an array that is an stdClass. The output of that array is as follows :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
)
What I would like to do is add two variables to this stdClass. They are "total_bookings" and "total_venues";
I currently am looping through the results and then getting a count to create the total. I would like to add those two vars to the end of that stdClass array.
My PHP is as follows :
$vendors = $this->po_model->get_all_vendors();
$this->template->set('total_vendors', count($vendors));
$count = 0;
foreach($vendors as $vendor)
{
$count++;
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$count]['total_venues'] = $total_venues;
$vendors[$count]['total_bookings'] = $total_bookings;
}
However, When I var_dump that my Array looks like this :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
[1] => Array
(
[total_venues] => 6
[total_bookings] => 14
)
)
So my question is, How do I add total_venues and total_bookings to that stdClass()?
Thanks
$myArray[$indexOfObject]->total_venues = 6;
$myArray[$indexOfObject]->total_bookings= 14;
Your example:
foreach($vendors as $key => $vendor)
{
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$key]->total_venues = $total_venues;
$vendors[$key]->total_bookings = $total_bookings;
}
its an object, you should use object notations, not array notations. also change your move your count++ below these two instructions
$vendors[$count]->total_venues = $total_venues;
$vendors[$count]->total_bookings = $total_bookings;
$count++;

Counting unique arrays inside the array in PHP?

I have some array containing other arrays:
Array
(
[0] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[1] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[2] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 24
[madeDatetime:protected] => 2011-04-18 11:31:26
[stake:protected] => 13.00
[status:protected] => 6
)
)
What's the best way of counting unique arrays?
Off the top of my head you could try:
$hashes = array();
$uniques = 0;
foreach($array as $slip) {
$hash = sha1(serialize($slip));
if(!in_array($hash, $hashes)) {
++$uniques;
$hashes[] = $hash;
}
}
var_dump($uniques); // prints total number of unique objects.
Edit:
#biakaveron's idea looks better though and could be adapted to:
$uniques = count(array_unique($array, SORT_REGULAR));
var_dump($uniques); // prints total number of unique objects.
This previous question has various solutions for removing duplicate arrays from within an array. If you implement any of them and then use sizeof() on the returned array you will have your solution.
eg:
<?php
$yourarray = array();
$tmp = array ();
foreach ($yourarray as $row)
if (!in_array($row,$tmp)) array_push($tmp,$row);
echo sizeof($tmp);
?>

Categories