Merge Array Issue - php

I have several arrays that all have this structure:
array (
526744 =>
array (
'completed' => 13,
'total' => 24,
'topics' =>
array (
),
'lessons' =>
array (
526745 => 1,
526747 => 1,
526749 => 1,
526751 => 0,
526757 => 0,
526759 => 0,
526761 => 1,
526763 => 0,
526765 => 0,
526767 => 1,
),
'last_id' => 526793,
),
526818 =>
array (
'completed' => 0,
'total' => 22,
'topics' =>
array (
),
'lessons' =>
array (
526819 => 0,
526821 => 1,
526823 => 1,
526845 => 0,
526847 => 1,
526849 => 1,
526859 => 1,
526861 => 1,
),
'last_id' => 526861,
),
)
The number in the outer-most element of the array is a course id. The list of numbers in the inner-most array elements are lesson ids.
I want to merge all of the arrays that contain this structure together. But only ones with the course id of 526744.
If I do something like this:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}
This works fine, but it merges the entire arrays, including all courses.
However if I specify the course_id like this:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$newarray = $new_array[526744];
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}
It no longer merges at all and just lists out the last array for that 1 single course specified.
Any ideas on what is causing this and how to fix it?
Thanks

I have check your code and found the issue, you have used $new_array[526744] which is wrong. it should be array($new_array[526744])
Check this code:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$newarray = array($new_array[526744]);
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}

Related

Add up the array values based on the same key (PHP)

I found a case where I had to add values based on the same week.
[{"week":"30","nilai":"230"},{"week":"30","nilai":"66"},{"week":"29","nilai":"72"},{"week":"29","nilai":"225"},{"week":"28","nilai":"213"},{"week":"28","nilai":"72"},{"week":"27","nilai":"191"},{"week":"27","nilai":"60"},{"week":"26","nilai":"176"},{"week":"26","nilai":"65"},{"week":"25","nilai":"167"},{"week":"25","nilai":"57"},{"week":"24","nilai":"209"},{"week":"24","nilai":"62"},{"week":"23","nilai":"180"},{"week":"23","nilai":"88"},{"week":"22","nilai":"178"},{"week":"22","nilai":"72"},{"week":"21","nilai":"164"},{"week":"21","nilai":"42"},{"week":"20","nilai":"193"},{"week":"20","nilai":"50"},{"week":"19","nilai":"186"},{"week":"19","nilai":"56"}]
the results I expect among others are like this
week => 30,
nilai=> 296
<?php
$input = '[{"week":"30","nilai":"230"},{"week":"30","nilai":"66"},{"week":"29","nilai":"72"},{"week":"29","nilai":"225"},{"week":"28","nilai":"213"},{"week":"28","nilai":"72"},{"week":"27","nilai":"191"},{"week":"27","nilai":"60"},{"week":"26","nilai":"176"},{"week":"26","nilai":"65"},{"week":"25","nilai":"167"},{"week":"25","nilai":"57"},{"week":"24","nilai":"209"},{"week":"24","nilai":"62"},{"week":"23","nilai":"180"},{"week":"23","nilai":"88"},{"week":"22","nilai":"178"},{"week":"22","nilai":"72"},{"week":"21","nilai":"164"},{"week":"21","nilai":"42"},{"week":"20","nilai":"193"},{"week":"20","nilai":"50"},{"week":"19","nilai":"186"},{"week":"19","nilai":"56"}]';
$input = json_decode($input, true);
$outArr = [];
foreach ($input as $arr) {
$week = $arr['week'];
if (key_exists($week, $outArr)) {
$outArr[$week] += $arr['nilai'];
} else {
$outArr[$week] = $arr['nilai'];
}
}
//optional sort - you may remove it
ksort($outArr);
$outArr2 = [];
foreach($outArr as $week => $nilai) {
$outArr2[] = ['week' => $week, 'nilai' => $nilai];
}
var_export($outArr2);
gives result:
array (
0 =>
array (
'week' => 19,
'nilai' => 242,
),
1 =>
array (
'week' => 20,
'nilai' => 243,
),
2 =>
array (
'week' => 21,
'nilai' => 206,
),
3 =>
array (
'week' => 22,
'nilai' => 250,
),
4 =>
array (
'week' => 23,
'nilai' => 268,
),
5 =>
array (
'week' => 24,
'nilai' => 271,
),
6 =>
array (
'week' => 25,
'nilai' => 224,
),
7 =>
array (
'week' => 26,
'nilai' => 241,
),
8 =>
array (
'week' => 27,
'nilai' => 251,
),
9 =>
array (
'week' => 28,
'nilai' => 285,
),
10 =>
array (
'week' => 29,
'nilai' => 297,
),
11 =>
array (
'week' => 30,
'nilai' => 296,
),
)
<?php
$input = '[{"week":"30","nilai":"230"},{"week":"30","nilai":"66"},{"week":"29","nilai":"72"},{"week":"29","nilai":"225"},{"week":"28","nilai":"213"},{"week":"28","nilai":"72"},{"week":"27","nilai":"191"},{"week":"27","nilai":"60"},{"week":"26","nilai":"176"},{"week":"26","nilai":"65"},{"week":"25","nilai":"167"},{"week":"25","nilai":"57"},{"week":"24","nilai":"209"},{"week":"24","nilai":"62"},{"week":"23","nilai":"180"},{"week":"23","nilai":"88"},{"week":"22","nilai":"178"},{"week":"22","nilai":"72"},{"week":"21","nilai":"164"},{"week":"21","nilai":"42"},{"week":"20","nilai":"193"},{"week":"20","nilai":"50"},{"week":"19","nilai":"186"},{"week":"19","nilai":"56"}]';
$input = json_decode($input, true);
$outArr = [];
foreach ($input as $arr) {
$week = $arr['week'];
if (key_exists($week, $outArr)) {
$outArr[$week]['week'] += $arr['nilai'];
} else {
$outArr[$week]['nilai'] = $arr['nilai'];
}
}
print_r($outArr);
?>
You can do that in a single loop using array_reduce.
This solution performs a true single pass without performing any additional searches in the array. I haven't benchmarked it, but I assume it is more performant.
<?php
$values = json_decode('[{"week":"30","nilai":"230"},{"week":"30","nilai":"66"},{"week":"29","nilai":"72"},{"week":"29","nilai":"225"},{"week":"28","nilai":"213"},{"week":"28","nilai":"72"},{"week":"27","nilai":"191"},{"week":"27","nilai":"60"},{"week":"26","nilai":"176"},{"week":"26","nilai":"65"},{"week":"25","nilai":"167"},{"week":"25","nilai":"57"},{"week":"24","nilai":"209"},{"week":"24","nilai":"62"},{"week":"23","nilai":"180"},{"week":"23","nilai":"88"},{"week":"22","nilai":"178"},{"week":"22","nilai":"72"},{"week":"21","nilai":"164"},{"week":"21","nilai":"42"},{"week":"20","nilai":"193"},{"week":"20","nilai":"50"},{"week":"19","nilai":"186"},{"week":"19","nilai":"56"}]');
print_r($values);
$result = array_reduce($values, function ($carry, $item) {
$carry[$item->week] = (object) [
'week' => $item->week,
'nilai' => ($carry[$item->week]->nilai ?? 0) + $item->nilai,
];
return $carry;
}, []);
print "RESULT ... \n";
print_r($result);
Running on Repl.it at https://repl.it/repls/NauticalDamagedBytecode
This solution gives you an array that is keyed by the week number so that you can directly access them without further looping inside the array to retrieve them.
If you do not want that and if you want the array to me indexed like 0, 1, 2, 3, ... them do $result = array_values(array_reduce( ... )) or $result = array_values($result)

Matching arrays and update value in array one

I'm trying to to update the value of array one, if it is found within array two, e.g:
$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish'];
I need to get the data back as:
$has_pets = ['Cat' => 1, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 1];
I've tried playing with the array_intersect() function and a foreach loop but for the life of me I could not get it working.
Cheers in advance
You can use array_merge() and array_count_values():
array_merge($all_pets, array_count_values($user_has));
Here's a demo
array_count_values() counts the occurrences of each value in the array, and returns an array with value => count pairs.
array_merge() merges the arrays, if they have the same string keys, then the later value for that key will overwrite the previous one.
You can use foreach to loop thru the array $user_has. Use isset() to check if the key exist in $all_pets. If it does, change the value.
$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish'];
foreach( $user_has as $value ) {
if ( isset( $all_pets[ $value ] ) ) $all_pets[ $value ]++;
}
This will result to:
Array
(
[Cat] => 1
[Dog] => 0
[Bird] => 0
[Rabbit] => 0
[Fish] => 1
)
<?php
$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish'];
$has_pets = array();
foreach ($user_has as $key => $pet) {
$has_pets[$pet]++;
}
print_r(array_merge($all_pets, $has_pets));
?>
Use foreach and in_array()
$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish'];
foreach($all_pets as $key=>$value){
if(in_array($key,$user_has){
$indexes = array_keys($user_has,$key);
$all_pets[$key]= count($indexes);
}
}

how to convert multi array to json multi array

i have foreach loop that returns multi-array from the database
and i want to convert this array to multi array in json ,
how to do this ?
php array example
Array
(
[0] => Array
(
[it_code] => 2894
[it_quantity] => 300
[it_price] => 0
[it_notes] =>
)
[1] => Array
(
[it_code] => 2894
[it_quantity] => 284
[it_price] => 0
[it_notes] =>
)
[2] => Array
(
[it_code] => 2894
[it_quantity] => 4
[it_price] => 0
[it_notes] =>
)
[3] => Array
(
[it_code] => 2894
[it_quantity] => 3
[it_price] => 0
[it_notes] =>
)
)
i want returned json to be like this format
[
['2894', 300, 0,''],
['2894', 284, 0,''],
['2894', 4, 0,''],
['2894', 3, 0,''],
['2894', 10, 0, '']
]
my code like this
$this->db->where("it_parent_item", $parent_id);
$this->db->select("d_items.it_code,d_items_type.it_ty_ar_desc,d_items.it_quantity,d_items.it_price,it_notes");
$this->db->join('d_items_type','d_items_type.it_ty_id=d_items.it_type','left');
$this->db->from("d_items");
$result = $this->db->get()->result_array();
echo "<pre>";
print_r($result);
echo "</pre>";
You can use array_values() and array_walk_recursive() to convert integer to string
$newArray = array();
foreach($sourceArray as $element) {
$newArray[] = array_values($element);
}
array_walk_recursive($newArray,
function(&$value, $key){
$value = (string)$value;
});
print_r (json_encode($newArray));
Note that other answers will give null instead of ''.
So, without using array_values, this code returns all values, but in case there is any null, it returns '' instead (as expected in the question):
$arr = array();
foreach($foo as $value){
$tmp = array();
foreach($value as $v){
$tmp[] = $v===null ? '' : $v;
}
$arr[] = $tmp;
}
echo json_encode($arr);
Output:
[[2894,300,0,""],[2894,284,0,""],[2894,4,0,""],[2894,3,0,""]]
[
[2894,300,0,""],
[2894,284,0,""],
[2894,4,0,""],
[2894,3,0,""]
]
This a copyable array:
$foo = array
(
0 => array
(
'it_code' => 2894,
'it_quantity' => 300,
'it_price' => 0,
'it_notes' => null
),
1 => Array
(
'it_code' => 2894,
'it_quantity' => 284,
'it_price' => 0,
'it_notes' => null
),
2 => Array
(
'it_code' => 2894,
'it_quantity' => 4,
'it_price' => 0,
'it_notes' => null
),
3 => Array
(
'it_code' => 2894,
'it_quantity' => 3,
'it_price' => 0,
'it_notes' => null
),
);
Here's the initial array (shown like a PHP array, but the same as your post):
$initialArray = array(
array(
"it_code" => 2894,
"it_quantity" => 300,
"it_price" => 0,
"it_notes" => '',
),
array(
"it_code" => 2894,
"it_quantity" => 284,
"it_price" => 0,
"it_notes" => '',
),
array(
"it_code" => 2894,
"it_quantity" => 4,
"it_price" => 0,
"it_notes" => '',
),
array(
"it_code" => 2894,
"it_quantity" => 3,
"it_price" => 0,
"it_notes" => '',
),
);
You can loop over each element, assigning just the values to a new set of arrays, like this:
$newArray = array();
foreach ($initialArray as $subArray)
{
$newArray[] = array_values($subArray);
}
The resulting array will look like this:
[[2894,300,0,""],[2894,284,0,""],[2894,4,0,""],[2894,3,0,""]]
Looks to me like you want to loop through your array so it's formatted how you want in PHP and then convert that PHP array into JSON:
$dataArray = array(); //The array containing your values
$jsonArray = array(); //The array which will be formatted for json
foreach($dataArray as $value){
$keylessValues = array_values($value);
$jsonArray[] = $keylessValues;
}
$jsonArray = json_encode($jsonArray); //This is now a JSON array storing your values
What we do here is move through the array and then take only the values with array_values() and put them into a new index in our $jsonArray.
Once we have moved through the entire array we can convert our newly formatted and populated array into JSON with json_encode()
It's worth noting that your values that are set as '' will come through as null. If you need those values as '' instead of null have a look at the answer #FirstOne gave.

Counting values within multidimensional arrays?

I have a large array where I basically need to count the number of uniques:
example array
The end result I am looking for something like
$result = array(
'A3D5' => array('P2' => 1, 'P3' => 1, 'P4' => 1, 'total' => 3),
'AE5S' => array('P4' => 1, 'total' => 1)
);
I've tried foreaching through but can't seem to figure out how to sort them into another key, something like $zone = "P{$array['zone']}"; $result[$zone][$prestige]++ or seems to kind of not work or just error.
$array = array(
"denizen" => array
(
"prestige" => 2,
"zone" => "A3D5",
"scope_frag" => 765
),
"생각" => array
(
"prestige" => 4,
"zone" => "A3D5",
"scope_frag" => 135
),
"Ryans" => array
(
"prestige" => 3,
"zone" => "A3D5",
"scope_frag" => 78
),
"지적인" => array
(
"prestige" => 2,
"zone" => "AE5S",
"scope_frag" => 481
)
);
foreach ($array as $group) {
$zones[$group["zone"]][] = $group["prestige"];
}
foreach ($zones as $name => $zone) {
$total = count($zone);
foreach ($zone as $prestige) {
$result[$name]["P".$prestige] += 1;
}
ksort($result[$name]);
$result[$name]["total"] = $total;
}
echo "<pre>";
print_r($result);
echo "</pre>";

PHP - Reorder array to match the order of another array

I have 1 array that has the right values that I need but it is out of order. I then have another array with the same keys and it is in the right order but the values are not what I need.
Here is my first array with the correct values but is out of order:
Array
(
[countTotal] => 7268
[zip] =>
[yearName] =>
[countZipRadius] =>
[Acura] => 1334
[Cadillac] => 511
[Ford] => 5423
)
Here is my second array with the right order but the wrong values:
Array
(
[countZipRadius] => 0
[zip] => 1
[yearName] => 2
[Acura] => 3
[Cadillac] => 4
[Ford] => 5
[countTotal] => 6
)
I am trying to figure out a way to create a new array with the right values from array 1 but that is in the order of array 2.
I have been playing with it for awhile and cannot seem to get it.
Any help would be great.
Thanks!
$c = array();
foreach (array_keys($b) as $k) {
$c[k] = $a[k];
}
You could use php's array_multisort function:
$original = array(
'countTotal' => 7268,
'zip' => '',
'yearName' => '',
'countZipRadius' => '',
'Acura' => 1334,
'Cadillac' => 511,
'Ford' => 5423,
);
$right = array(
'countZipRadius' => 0,
'zip' => 1,
'yearName' => 2,
'Acura' => 3,
'Cadilac' => 4,
'Ford' => 5,
'countTotal' => 6
);
//make sure both arrays are in the same order
ksort($original);
ksort($right);
array_multisort($right, $original);
print_r($original);
When you give it two arrays with the same number of elements it sorts both arrays, based on the order of the first array - in this case the 0, 1, 2, 3, etc. values in $right
Create a New Array (Array C)
Use a FOR loop to go through Array B
For each value in Array B, get the value with the same key from Array A and set Array C append those values to Array C. This will put them in the correct order in C.
Using scones' method:
$original = array(
'countTotal' => 7268,
'zip' => '',
'yearName' => '',
'countZipRadius' => '',
'Acura' => 1334,
'Cadillac' => 511,
'Ford' => 5423,
);
$right = array(
'countZipRadius' => 0,
'zip' => 1,
'yearName' => 2,
'Acura' => 3,
'Cadilac' => 4,
'Ford' => 5,
'countTotal' => 6
);
foreach ($right as $key => $value) {
$new[$key] = $original[$key];
}
print_r($new);
$array = array('a' => 100, 'b' => '5');
$newArray = array_combine(array_keys($array), range(0, count($array) - 1));
var_dump($newArray);

Categories