PHP - combine values from Objectlist with same key - php

I have an objectlist:
$deliveryOptions =
Array ( [0] => stdClass Object ( [item_id] => 55 [value] => delivery-online )
[1] => stdClass Object ( [item_id] => 55 [value] => delivery-campus )
[2] => stdClass Object ( [item_id] => 56 [value] => delivery-campus )
[3] => stdClass Object ( [item_id] => 81 [value] => delivery-blended )
)
I need to format it to an array:
$combined =
( [item_id] => 55 [course-delivery] => array( "delivery-online","delivery-campus")
( [item_id] => 56 [course-delivery] => delivery-campus )
( [item_id] => 81 [course-delivery] => delivery-blended )
My code so far:
foreach ($deliveryOptions as $row)
{
$temp = array('item_id'=>$row->item_id,
'course-delivery'=>$row->value
);
$course[] = $temp;
}
foreach ($course as $row)
{
$match = array_search($row['item_id'], array_column($combined, 'item_id'));
if(is_numeric($match))
{
$combined[$match]['course-delivery'][] = $row['course-delivery'];
}
else{
array_push($combined, [
'item_id' => $row['item_id'],
'course-delivery' => array($row['course-delivery'])
]);
}
}
The format of $combined might seem odd, but I have three different queries creating different object lists that all need to be combined into one JSON array based on 'item_id' as the key.
I have the part where all three get combined working, this new array configuration comes from a checkbox situation, thus the need to combine the different values off the same item_id.

No need for another foreach, you just create the structure along the way. First, initialize the container for the particular item_id.
When an item_id hits again and is not an array, just overwrite it, use the first value (string) and turn it to an array and finally push the value.
$deliveryOptions = [
(object) ['item_id' => 55, 'value' => 'delivery-online'],
(object) ['item_id' => 55, 'value' => 'delivery-campus'],
(object) ['item_id' => 56, 'value' => 'delivery-campus'],
(object) ['item_id' => 81, 'value' => 'delivery-blended'],
];
$combined = [];
foreach ($deliveryOptions as $row) {
if (!isset($combined[$row->item_id])) { // initialize if it doesn't exist
$combined[$row->item_id] = (array) $row; continue;
}
if (!is_array($combined[$row->item_id]['value'])) { // if another occurence
$temp = $combined[$row->item_id]['value']; // get the string initial value
$combined[$row->item_id]['value'] = []; // turn it into an array
$combined[$row->item_id]['value'][] = $temp; // and reassign and push inside the array
}
$combined[$row->item_id]['value'][] = $row->value; // push the value in the array
}
// $combined = array_values($combined); // array key reindex if needed
Sample output

Related

Merge arrays in an array and add values

I need to take an array like this:
Array
(
[0] => Array
(
[county_code] => 54045
[count] => 218
)
[1] => Array
(
[county_code] => 54045
[count] => 115
)
[2] => Array
(
[county_code] => 54051
[count] => 79
)
)
And merge all arrays with the same county_code adding the count, like this:
Array
(
[0] => Array
(
[county_code] => 54045
[count] => 333
)
[1] => Array
(
[county_code] => 54051
[count] => 79
)
)
There will be multiple instances of multiple county codes.
Can anyone point me in the right direction?
Try this out:
// your example array
$array = [
[
"county_code" => 54045,
"count" => 218
],
[
"county_code" => 54045,
"count" => 115
],
[
"county_code" => 54051,
"count" => 79
]
];
// intrim step to collect the count.
$intrimArray = [];
foreach( $array as $data ){
$countyCode = $data["county_code"];
if (!$intrimArray[$countyCode]) {
$intrimArray[$countyCode] = $data["count"];
} else {
$intrimArray[$countyCode] = $intrimArray[$countyCode] + $data["count"];
}
}
// build the final desired array using interim array.
$finalArray = [];
foreach($intrimArray as $countyCode => $totalCount) {
array_push($finalArray, [
"county_code" => $countyCode,
"count" => $totalCount
]);
}
var_dump($finalArray);
As promised:
<?php
$initial_array = [
['country_code' => 54045, 'count' => 218],
['country_code' => 54045, 'count' => 115],
['country_code' => 54051, 'count' => 79],
];
$synth = [];
foreach ($initial_array as $sa) { # $sa: subarray
if (!isset($synth[$sa['country_code']])) {
$synth[$sa['country_code']] = 0;
}
$synth[$sa['country_code']] += $sa['count'];
}
print_r($synth); # Synthesis array: keys are country codes, values are cumulative counts.
# If you need the same format for both the initial and synthesis arrays, then continue with this:
$synth2 = [];
foreach ($synth as $k => $v) {
$synth2[] = ['country_code' => $k, 'count' => $v];
}
print_r($synth2);
?>
A fiddle for this code: https://3v4l.org/M8tkb
Best regards

Pushing a sub array into the same array

I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>

Checking if array value exists in a PHP multidimensional array

I have the following multidimensional array:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
I'm currently using a foreach loop to extract the values from the array:
foreach ($result as $key => $sub)
{
...
}
But I was wondering how do I see whether a value within the array already exists.
So for example if I wanted to add another set to the array, but the id is 1 (so the person is Jonah) and their score is 5, can I add the 5 to the already created array value in id 0 instead of creating a new array value?
So after the loop has finished the array will look like this:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 32 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
What about looping over your array, checking for each item if it's id is the one you're looking for ?
$found = false;
foreach ($your_array as $key => $data) {
if ($data['id'] == $the_id_youre_lloking_for) {
// The item has been found => add the new points to the existing ones
$data['points'] += $the_number_of_points;
$found = true;
break; // no need to loop anymore, as we have found the item => exit the loop
}
}
if ($found === false) {
// The id you were looking for has not been found,
// which means the corresponding item is not already present in your array
// => Add a new item to the array
}
you can first store the array with index equal to the id.
for example :
$arr =Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
//So now you can check the array $new for if the key exists already
if(array_key_exists(1, $new)){
$new[1]['points'] = 32;
}
Even though the question is answered, I wanted to post my answer. Might come handy to future viewers. You can create new array from this array with filter then from there you can check if value exist on that array or not. You can follow below code. Sample
$arr = array(
0 =>array(
"id"=> 1,
"name"=> "Bangladesh",
"action"=> "27"
),
1 =>array(
"id"=> 2,
"name"=> "Entertainment",
"action"=> "34"
)
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
if(array_key_exists(1, $new)){
echo $new[1]['id'];
}
else {
echo "aaa";
}
//print_r($new);

PHP/MySQL: Recreate multidimensional array from existing array

I've got an multi-array (currently with objects) that I want to reorder based on a specific key/value.
Array
(
[0] => stdClass Object
(
[task_id] => 1
[task_title] => Title
[users_username] => John
)
[1] => stdClass Object
(
[task_id] => 2
[task_title] => Title
[users_username] => John
)
[2] => stdClass Object
(
[task_id] => 3
[task_title] => Title
[users_username] => Mike
)
)
I'd like to reorder it to get multi-arrays by user_name, so I can cycle through the task by username.
Array
(
[John] => Array
(
[0] => Array
(
[task_id] => 1
[title] => Title
)
[1] => Array
(
[task_id] => 2
[title] => Title
)
)
[Mike] => Array
(
[0] => Array
(
[task_id] => 3
[title] => Title
)
)
)
Is it possible to recreate my array to an array like that above?
Updated version of the code
<?php
$it0 = (object) array('task_id' => 1,'task_title' => 'Title','users_username' => 'John');
$it1 = (object) array('task_id' => 2,'task_title' => 'Title','users_username' => 'John');
$it2 = (object) array('task_id' => 3,'task_title' => 'Title','users_username' => 'Mike');
$array = array($it0,$it1,$it2);
$return = array();
foreach($array as $id => $value){
$return[$value->users_username][] = array('task_id' => $value->task_id,'title' => $value->task_title);
}
var_dump($return);
Yes, it is possible.
You'll have to loop through your current array and create a new array to do it.
example:
$new_array = array();
foreach ($array as $row)
{
$new_row = array(
'task_id' => $row->task_id,
'title' => $row->task_title,
);
$name = $row->users_username;
if (isset($new_array[$name]))
{
$new_array[$name][] = $new_row;
}
else
{
$new_array[$name] = array($new_row);
}
}
Now $new_array contains the new array exactly like the one you're asking for.
Then you can sort it with
ksort($new_array);
There may be another way to do this, with some built-in function, but sometimes I'd rather just do it myself, and know how it is working, without having to look up the documentation.
The approach:
Iterate through all of the first array, looking at [users_username] and putting them into a new array.
Code:
$dst_array = array();
foreach ($src_array as $val)
{
$user = $val->users_username;
// TODO: This check may be unnecessary. Have to test to find out.
// If this username doesn't already have an array in the destination...
if (!array_key_exists($user, $dst_array))
$dst_array[$user] = array(); // Create a new array for that username
// Now add a new task_id and title entry in that username's array
$dst_array[$user][] = array(
'task_id' => $val->task_id
'title' => $val->title
);
}
Just something like this (maybe not 100% PHP code):
foreach ( $obj : $oldArray ) {
$newTask['task_id'] = $obj->task_id;
$newTask['title'] = $obj->title;
$newArray[$oldName][] = $newTask;
}
If you want to order it; you can just call a order function afterwards.

How to output an array based on primary keys and foreign keys

Considering this array
Array
(
[0] => Array
(
[id] => 51
[category_id] => 37
[title] => Sims
)
[1] => Array
(
[id] => 37
[category_id] => 26
[title] => Blackberry
)
[2] => Array
(
[id] => 26
[category_id] => 0
[title] => Mobile Device
)
I would like to be able to print out:
Mobile Device > Blackberry > Sims
Based on the relationship between category_id and id.
Can you use the id as the key into the array? It will make your life a bit simpler. For example, if you define your array:
Array
(
[51] => Array
(
[id] => 51
[category_id] => 37
[title] => Sims
)
[37] => Array
(
[id] => 37
[category_id] => 26
[title] => Blackberry
)
[27] => Array
(
[id] => 26
[category_id] => 0
[title] => Mobile Device
)
Then you can write code like:
//assume $a is your array, defined above
//and that you have used the id for the array key
$id = 51
do {
print $a['title'];
$id = $a['category_id'];
}while($id != 0);
EDIT: array_multisort probably isn't cleanest way to do this.
<?php
$array = Array(
array('id' => 51, 'category_id' => 37, 'title' => 'Sims'),
array('id' => 37, 'category_id' => 26, 'title' => 'Blackberry'),
array('id' => 26, 'category_id' => 0, 'title' => 'Mobile Device'));
// First build an associative array ID->Object
$map = array();
foreach( $array as $value )
{
$map[$value['id']] = $value;
}
// Then build your path
$path = array();
$value = $array[0];
while( true )
{
$path[] = $value['title'];
if( $value['category_id'] == 0 )
{
break;
}
$value = $map[$value['category_id']];
if( !isset($value) )
{
die("Data Inconsistency");
}
}
// Display path
echo implode(array_reverse($path), ' > ');
?>
Try array_multisort()
Does your original array also contains entries that are to be left out?
If not, use this:
$sort_array = array();
foreach ($original_array as $key => $value) {
$sort_array[] = $value['category_id'];
}
array_multisort($sort_array, SORT_ASC, $original_array);
The above will sort $original_array based on the category_id index.
If your array contains entries that have nothing to do with the rest, and you want to leave them out, you have to use something like this:
// remap keys based on category_id
$parts = array();
foreach ($original_array as $array) {
$parts[$array['category_id']] = $array;
}
// build tree list
$category_id = 0;
$result = array();
while (isset($parts[$category_id])) {
$result[] = $parts[$category_id]['title'];
$category_id = $parts[$category_id]['id'];
}
echo implode(' > ', $result);

Categories