Need to push the key and value inside associative Array? - php

I need to push the more key and its value inside the array. If I use below code first key pair replaced by 2nd one.
For your Reference:
Code Used:
foreach ($projectData['projectsections'] as $key => $name) {
$projectData['projectsections'][$key] = ['name' => $name];
$projectData['projectsections'][$key]= ['id' => '1'];
}
Current result:
'projectsections' => [
(int) 0 => [
'id' => '1'
],
(int) 1 => [
'id' => '1'
]
],
Expected:
'projectsections' => [
(int) 0 => [
'name' => 'test1',
'id' => '1'
],
(int) 1 => [
'name' => 'test2',
'id' => '1'
]
],
How can I build this array in PHP?? Any one help??

You need to either add the entire array:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
Or add with the key name:
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';

With
$projectData['projectsections'][$key] = ['name' => $name];
$projectData['projectsections'][$key]= ['id' => '1'];
you are setting a new Array for that $key. This is not what you want.
This should work:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];

Change it to :
foreach ($projectData['projectsections'] as $key => $name) {
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
}

Related

PHP: Remove duplicate elements and get the latest data in the array

$arr = [
[
"id" => '6230061c0e88d709ca0d7bbc',
'name' => 'Mobile SamSung',
'slug' => 'mobile-samsung',
'createdAt' => '1648006346'
],
[
"id" => '5d1eff529a426778d4b92383',
'name' => 'Mobile Iphone',
'slug' => 'mobile-iphone',
'createdAt' => '1647314181'
],
[
"id" => '5d1eff6b9a426778d4b92dc4',
'name' => 'Mobile SamSung',
'slug' => 'mobile-samsung',
'createdAt' => '1647314460'
],
[
"id" => '5f894011266aea580b028cb0',
'name' => 'Mobile LG',
'slug' => 'mobile-lg',
'createdAt' => '1647314456'
]
];
I have an array, and in this array there are many duplicate subarrays, now I want to remove the duplicate arrays inside, keeping only the data with the latest createdAt. Please give me your opinion. Thanks
I would like to get an array like this:
$arr = [
[
"id" => '6230061c0e88d709ca0d7bbc',
'name' => 'Mobile SamSung',
'slug' => 'mobile-samsung',
'createdAt' => '1648006346'
],
[
"id" => '5d1eff529a426778d4b92383',
'name' => 'Mobile Iphone',
'slug' => 'mobile-iphone',
'createdAt' => '1647314181'
],
[
"id" => '5f894011266aea580b028cb0',
'name' => 'Mobile LG',
'slug' => 'mobile-lg',
'createdAt' => '1647314456'
]
];
You should not make more than one pass over your data. Just use the name values as temporary keys, then only retain a duplicate row's data if its createAt value is greater than what is stored. Re-index the array when you are finished looping.
Code: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($result[$row['name']]) || (int)$row['createdAt'] > (int)$result[$row['name']]['createdAt']) {
$result[$row['name']] = $row;
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'id' => '6230061c0e88d709ca0d7bbc',
'name' => 'Mobile SamSung',
'slug' => 'mobile-samsung',
'createdAt' => '1648006346',
),
1 =>
array (
'id' => '5d1eff529a426778d4b92383',
'name' => 'Mobile Iphone',
'slug' => 'mobile-iphone',
'createdAt' => '1647314181',
),
2 =>
array (
'id' => '5f894011266aea580b028cb0',
'name' => 'Mobile LG',
'slug' => 'mobile-lg',
'createdAt' => '1647314456',
),
)
Potentially helpful:
Laravel - fetch unique rows from table having highest value in x column
Remove duplicate objects from array based on one value, keep lowest of other value in PHP?
Filter rows with unique column value and prioritize rows with a particular value in another column
How to get max amount of value in same key in array
Explanation:
In this solution, I have gotten the data with a unique slug key with the latest createdAt key. we can have any unique key that matches into the multidimensional array and get the result whatever we want.
Code:
$newArray = [];
foreach ($array as $key => $value) {
$findIndex = array_search($value['slug'], array_column($newArray, 'slug'));
if ($findIndex === false) {
$newArray[] = $value;
} elseif ($findIndex !== false && $newArray[$findIndex]['createdAt'] <= $value['createdAt']) {
$newArray[$findIndex] = $value;
}
}
print_r($newArray);
Demo Link (With your Data): https://3v4l.org/f4kRM
Demo Link (Customized Data with my way): https://3v4l.org/sj4MW
First sort on created at, then remove duplicates.
<?php
$arr = [
[
"id" => '6230061c0e88d709ca0d7bbc',
'name' => 'Mobile SamSung',
'slug' => 'mobile-samsung',
'createdAt' => '1648006346'
],
[
"id" => '5d1eff529a426778d4b92383',
'name' => 'Mobile Iphone',
'slug' => 'mobile-iphone',
'createdAt' => '1647314181'
],
[
"id" => '5d1eff6b9a426778d4b92dc4',
'name' => 'Mobile SamSung',
'slug' => 'mobile-samsung',
'createdAt' => '1647314460'
],
[
"id" => '5f894011266aea580b028cb0',
'name' => 'Mobile LG',
'slug' => 'mobile-lg',
'createdAt' => '1647314456'
]
];
function sort_objects_by_created($a, $b) {
if($a['createdAt'] == $b['createdAt']){ return 0 ; }
return ($a['createdAt'] > $b['createdAt']) ? -1 : 1;
}
// Let's sort
usort($arr, 'sort_objects_by_created');
$slugs = [];
$result = [];
// Loop object
foreach($arr as $phone) {
// If slug is not found, add to result
if (!in_array($phone['slug'], $slugs)){
$slugs[] = $phone['slug'];
$result[] = $phone;
}
}
var_dump($result,$slugs);
Might be worth a note, that you might be able to improve this upstream when creating your array. (always look upstream!)
If you can give you base array a key of created At you can use Array sorting, which which will this step more effecient....
E.g.
$arr = [];
$arr[2022-01-01] = Array('id' => 123, 'name' = 'abc');
$arr[2022-04-01] = Array('id' => 123, 'name' = 'abc');
$arr[2022-08-01] = Array('id' => 123, 'name' = 'abc');

Remove a array from an multidimensional array using object value in laravel

i need to remove duplicate array from below array.
first and third arrays are same, consider only "id"
$data = [
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
],
[
'id' => 'test_fun1%test',
'text' => 'test_fun1',
'data-value' => 'test',
],
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
'selected' => true
]
];
i'm tried to below code.
-> array_unique($data);
-> array_map("unserialize", array_unique(array_map("serialize", $data)));
Expected Output
$data = [
[
'id' => 'test_fun1%test',
'text' => 'test_fun1',
'data-value' => 'test',
],
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
'selected' => true
]
];
array_unique is not going to work since you have "selected" in the third array. I agree with the comments that this is quite unclear but to me it seems you're looking for a custom filtration rule, so a plain old foreach is the tool for the job.
<?php
$data = [
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
],
[
'id' => 'test_fun1%test',
'text' => 'test_fun1',
'data-value' => 'test',
],
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
'selected' => true
]
];
$filtered = [];
foreach ($data as $row) {
$id = $row['id'];
$selected = $row['selected'] ?? false;
if (isset($filtered[$id])) {
if (!$selected) {
continue;
}
unset($filtered[$id]);
}
$filtered[$id] = $row;
}
// optional use if you don't want ids for keys
$filtered = array_values($filtered);
print_r($filtered);

How to transform array of arrays into grouped arrays containing key and values?

Following is the input array:
$input = [
[
'id' => 96,
'shipping_no' => 212755-1,
'part_no' => 'reterty',
'description' => 'tyrfyt',
'packaging_type' => 'PC'
],
[
'id' => 96,
'shipping_no' => 212755-1,
'part_no' => 'dftgtryh',
'description' => 'dfhgfyh',
'packaging_type' => 'PC'
],
[
'id' => 97,
'shipping_no' => 212755-2,
'part_no' => 'ZeoDark',
'description' => 's%c%s%c%s',
'packaging_type' => 'PC'
]
];
I want the above to be transformed into like this:
$output = [
[
'key' => 96,
'value' => [
[
'shipping_no' => 212755-1,
'part_no' => 'reterty',
'description' => 'tyrfyt',
'packaging_type' => 'PC'
],
[
'shipping_no' => 212755-1,
'part_no' => 'dftgtryh',
'description' => 'dfhgfyh',
'packaging_type' => 'PC'
]
]
],
[
'key' => 97,
'value' => [
[
'shipping_no' => 212755-2,
'part_no' => 'ZeoDark',
'description' => 's%c%s%c%s',
'packaging_type' => 'PC'
]
]
]
];
I have tried to implement it like this:
$result = [];
foreach ($input as $value) {
$result[] = ['key' => $value['id'], 'value' => ['shipping_no' => $value['shipping_no'], 'part_no' => $value['part_no'], 'description' => $value['description'], 'packaging_type' => $value['packaging_type']]];
}
It is not getting grouped based on common key. Please help me with the possible approach that I should take to solve this.
I can see that you've done a good job of crafting the new subarray structure, but the grouping should come first and because of how the grouping is done with temporary keys, the restructuring code can be simplified.
Code: (Demo)
$result = [];
foreach ($input as $row) {
$id = $row['id'];
unset($row['id']);
if (isset($result[$id])) {
$result[$id]['value'][] = $row;
} else {
$result[$id] = [
'key' => $id,
'value' => [$row]
];
}
}
var_export(
array_values($result)
);
To explain the process:
As you iterate the input array, cache the id of each encountered row of data.
Because you do not wish to retain the $row['id'] in your value subarray, you can now safely remove that element from the $row.
Then check if there is an existing group for the current $id with isset($result[$id]).
If the group already exists, then you can merely push the $row data as a new indexed row into the group's value subarray.
If the group does not already exist, then it needs to have all of the desired structure declared/populated. This means that the key element is declared and the value subarray must be declared with its first entry.
Finally, if you don't want the first level keys remove them with array_values().

PHP merge duplicate key in array

i got response (json) from web service and converted / decoded it into php array.
converted array php:
$data = [
[
'id' => '01',
'name' => 'ABC',
'label' => 'color',
'value' => '#000000'
],[
'id' => '01',
'name' => 'ABC',
'label' => 'active',
'value' => true
],[
'id' => '02',
'name' => 'DEF',
'label' => 'color',
'value' => '#ffffff'
],[
'id' => '02',
'name' => 'DEF',
'label' => 'active',
'value' => false
]
];
expected array output:
$data = [
[
'id' => '01',
'name' => 'ABC',
'color' => '#000000',
'active' => true,
],[
'id' => '02',
'name' => 'DEF',
'color' => '#ffffff',
'value' => false
]
];
What php function is suitable for that case? thanks in advance
You can simple use foreach
$r = [];
foreach($data as $v){
if(isset($r[$v['id']])){
$r[$v['id']][$v['label']] = $v['value'];
}else{
$r[$v['id']] = [
'id' => $v['id'],
'name' => $v['name'],
$v['label'] => $v['value']
];
}
}
Live example : https://3v4l.org/ilkGG
$data = json_decode($data); //decode the json into a php array
foreach ($data as $key=>$subArray){ //loop over the array
//check and see if value is either true/false
if (is_bool($subArray['value'])){
$processedArray[] = $subArray; //build output
}
}
print_r($processedArray); //output/dump array for debugging
In this case, you have to loop through the array and remove duplicates, Try the given way
$data = json_decode($data , true);
$filtered = array();
for($i = 0 ; $i < count($data) ; $i++){
if(!array_key_exist($data[$i]['id'] , $filtered )){
$filtered [$data[$i]['id']] = $data[$i];
continue;
}
}
$filtered = array_values($filtered);

How to compare two associative arrays by key

I am trying to compare two associative arrays and get the difference based upon the value and also based upon the key. I have tried using an array_filter with a closure
The two arrays are like so:
Array 1
$newArr = [
0 => [
'id' => 'UT5',
'qty' => '4'
],
1 => [
'id' => 'WRO',
'qty' => '3'
],
2 => [
'id' => 'SHO',
'qty' => '3'
]
];
Array 2
$oldArr = [
0 => [
'id' => 'SHO',
'qty' => '1'
],
1 => [
'id' => 'UT5',
'qty' => '2'
],
];
My desired output is as follows:
array(3)
{
["UT5"]=> int(2)
["SHO"]=> int(2)
["WRO"]=> int(3)
}
I have gotten this far:
<?php
$newArr = [
0 => [
'id' => 'UT5',
'qty' => '4'
],
1 => [
'id' => 'WRO',
'qty' => '3'
],
2 => [
'id' => 'SHO',
'qty' => '3'
]
];
$oldArr = [
0 => [
'id' => 'SHO',
'qty' => '1'
],
1 => [
'id' => 'UT5',
'qty' => '2'
],
];
$toAdd = [];
foreach ($newArr as $item) {
$itemsToAdd = array_walk($oldArr, function ($k) use ($item, &$toAdd) {
if ($k['id'] == $item['id']) {
$toAdd[$k['id']] = max($k['qty'], $item['qty']) - min($k['qty'], $item['qty']);
}
});
}
var_dump($toAdd); die();
However with this function, my current output is:
array(2) {
["UT5"]=> int(2)
["SHO"]=> int(2)
}
Note that WRO is missing. Is there a way that I can add a conditional to accurately check for this? I have tried a few solution such as !in_array and else but neither are giving me the desired output.
Any help is appreciated! Thanks!
That's an easy one, your code saves a value ONLY if the key is present in both arrays. Just add a clause to check if the key DOESN'T exist in the old array. (also do the opposite in case the old array has a key the new one doesn't have)
if (!isset(old array [ new array key ]){
$newArray[new array key] = new array key and values;
Your program structure is optimized for the computer and is too complex to follow as a human, I rewrote it entirely.
<?php
$newArr = [0 => ['id' => 'UT5', 'qty' => '4'], 1 => ['id' => 'WRO', 'qty' => '3'], 2 => ['id' => 'SHO', 'qty' => '3']];
$oldArr = [0 => ['id' => 'SHO', 'qty' => '1'], 1 => ['id' => 'UT5', 'qty' => '2'], ];
$newReset = [];
foreach( $newArr as $item ) {
$newReset[$item['id']] = $item['qty'];
}
$oldReset = [];
foreach( $oldArr as $item ) {
$oldReset[$item['id']] = $item['qty'];
}
foreach( $newReset as $key => $val ) {
if( isset( $oldReset[$key] ) ) {
$toAdd[$key] = max( $oldReset[$key], $val ) - min( $oldReset[$key], $val );
}
else $toAdd[$key] = intval($val);
}
var_dump( $toAdd );
And here's the result.
array(3) {
["UT5"]=>
int(2)
["WRO"]=>
int(3)
["SHO"]=>
int(2)
}
Make it in one pass
$toAdd = [];
foreach ($newArr as $item)
$toAdd[$item['id']] = $item['qty'];
foreach ($oldArr as $item)
if (isset($toAdd[$item['id']]))
$toAdd[$item['id']] = abs($toAdd[$item['id']] - $item['qty']);
else
$toAdd[$item['id']] = abs($item['qty']);
print_r($toAdd);

Categories