How to Replace One Array index with another array in Php [duplicate] - php

This question already has answers here:
PHP array replace after matching value [duplicate]
(2 answers)
Closed 2 months ago.
Am using Php as my serverside scripting language.In my project I used Json string decoded into array.
My problem is how to overwrite the existing array index based on an array value.
my existing array looks like :
$array1 =[
{
"Name":"apple",
"color":"red",
"property":[
{
"p1":"value1",
"p2":"value2"
}
]
},
{
"Name":"Grape",
"color":"violet",
"property":[
{
"p1":"value1",
"p2":"value2"
}
]
}
];
and the updated array content looks:
$upadatearray = [
{
"Name":"apple",
"color":"green",
"property":[
{
"p1":"newvalue",
"p2":"newvalue2"
}
]
}
];
I want to update the existing $array1 with new $upadatearray , bsed on the "Name" .If it is same then replace.
I want to look like:
$finalarray =[
{
"Name":"apple",
"color":"green",
"property":[
{
"p1":"newvalue",
"p2":"newvalue2"
}
]
},
{
"Name":"Grape",
"color":"violet",
"property":
[
{
"p1":"value1",
"p2":"value2"
}
]
}
];
I tried this :
for($j=0;$j<count($array1);$j++)
{
if($array1[$j]['Name'] == $upadatearray[0]['Name'])
$finalarray = array_replace($array1[$j],$upadatearray[0]);
}
But it will not work correctly.Is there any possible solution ?

Let you have this two arrays:
$array1 ='[{"Name":"apple","color":"red","property":[{"p1":"value1","p2":"value2"}]},{"Name":"Grape","color":"violet","property":[{"p1":"value1","p2":"value2"}]}]';
$upadatearray = '[{"Name":"apple", "color":"green", "property":[{"p1":"newvalue","p2":"newvalue2"}]}]';
$array1 = json_decode($array1, true);
$upadatearray = json_decode($upadatearray, true);
You can use array_replace function. But to make it replace items based on the Name column you should first make this column a key of array
function make_column_key($arr, $col_name) {
$keys = array_column($arr, $col_name);
$result = array_combine($keys, $arr);
return $result;
}
$array1 = make_column_key($array1, 'Name');
$upadatearray = make_column_key($upadatearray, 'Name');
And now simply use array_replace
$finalarray = array_replace($array1, $upadatearray);
If you don't need Name be the key of final array, you can get only values:
$finalarray = array_values($finalarray);

hi I think this code will help you.
//what i did is i created a final array variable which gets the value of old array.
$finalArray = $array1;
//then i perform a foreach loop for old array
foreach ($array1 as $key => $oldarray) {
//inside the updated array
foreach ($upadatearray as $key => $newarray) {
//if old array name and new array name is same replace content on the final array
if ($oldarray['Name'] == $newarray['Name']) {
$finalArray['Name'] = $newarray['Name'];
}
}
}

Related

Laravel check an array of object which contain in another array

I would like to get check my array of the object have title and id. I want to get all the array of objects where id exists in the existing array.
I tried using array_diff or array_intersect but error stating that it is supposed to be an array.
if (!empty(session('selected_movies'))) {
$current_movies = array_intersect($allMovies, session('selected_movies'));
}
The array of objects data
[
{
"id":"05595dd2-2f13-11ea-9e3f-42010a940008",
"title":"Harry Potter"
},
{
"id":"247d20cd-2f13-11ea-9e3f-42010a940008",
"title":"Tom and Jerry"
}
]
Existing array data
["247d20cd-2f13-11ea-9e3f-42010a940008", "51141418-4fb1-11ea-a428-7a79190f5c7d"]
You could do a simple foreach and just unset if its missing desired id
<?php
//Enter your code here, enjoy!
$array = json_decode('[
{
"id":"05595dd2-2f13-11ea-9e3f-42010a940008",
"title":"Harry Potter"
},
{
"id":"247d20cd-2f13-11ea-9e3f-42010a940008",
"title":"Tom and Jerry"
}
]');
$check = ["247d20cd-2f13-11ea-9e3f-42010a940008", "51141418-4fb1-11ea-a428-7a79190f5c7d"];
foreach($array as $index => $current){
if(!in_array($current->id,$check)) unset($array[$index]);
}
print_r($array);
alternativly if you want to create a new array
$mah = [];
foreach($array as $index => $current){
if(in_array($current->id,$check)) array_push($mah,$current);
}
print_r($mah);

php get value based on key in array

I am trying to get a new array with all the codes that I get from an array called $houses. I loop thru it. To get the codes I tried $house['code'] This works in the dd but not in the $code = $house['code'].
I would like to know why and what the solution to this is.
$houses = $project['data']['houses'];
$codes = [];
foreach($houses as $house) {
$code = array_column($house, 'code');
//dd($house['code']); //Returns the code "AB12-CD34-EF56-GH78"
if(!$code) {
continue;
} else {
array_push($codes, $code);
}
}
dd($codes); //Returns []
EDIT:
var_dump $houses:
array:60 [
0 => array:30 [
"id" =>
"city" => ""
"code" => "AB12-CD34-EF56-GH78"
"streetName" => ""
"houseNumber" => ""
//And some other stuff that is not relevant to the question
]
]
array_column is for recovering a column from an array inside an array of arrays. $house is a simple array and doesn't contain arrays in it. just use $house['code']
$houses = $project['data']['houses'];
$codes = [];
foreach($houses as $house) {
if(isset($house['code']) && $house['code']) {
$codes[] = $house['code'];
}
}
dd($codes); //Returns ["AB12-CD34-EF56-GH78","AB12-CD34-EF56-GH79", ....]
Instead of this loop, you can simply extract all codes from subarrays with:
$houses = $project['data']['houses'];
$codes = array_column($houses, 'code');
dd($codes);

how to remove empty array value with key in php?

I am getting an array similar to the following one.
{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}
If form data values are null, I want to replace that key's value with the value of the next key.
Like above, after value 5, I have null values. It needs to be like this:
"final_data":["1","2","4","5","fill this with 6","remove this"]
"final_data":["1","2","4","5","6"] like this
I tried array_filter(), but it didn't help.
If the response is in json format then ...
$json = '{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}';
$array = json_decode($json, TRUE);
foreach($array as $index => $a) {
$array[$index] = array_filter($a);
}
print_r($array);
https://eval.in/866379
Update:
foreach($array as $index => $a) {
$array[$index] = array_value(array_filter($a));
}
https://eval.in/866522
try following code,
foreach($myarray as $key=>$value)
{
if(is_null($value) || $value == '')
unset($myarray[$key]);
}
Try this array_filter() with array_map() and array_values()
<?php
$array = array("form_data" => array("1","2","4","5","","6"), "final_data" => array("1","2","4","5","","6"));
function filterMe($paraArr){
return array_values(array_filter($paraArr));
}
$array = array_map("filterMe",$array);
echo "<pre>";
print_r($array);
check the output here https://eval.in/866401

Formatting an Array in php (3 into one)

So currently I have an array that pulls data based on an attribute and it puts the data in its own seperate array. What I need to do is to put these 3 arrays into one, so if one of them is null, it won't give me errors. It should be fairly simply but I can't wrap my head around it.
//CV eqpValue
if (is_array(FullDataResponse->dlr->DesignLayoutRecord)) {
foreach(FullDataResponse->dlr->DesignLayoutRecord as $DesignLayoutRecord_key => $DesignLayoutRecord_value ) {
if ($DesignLayoutRecord_value->cktEqpOptions->CktEqpOptions && is_array($DesignLayoutRecord_value->cktEqpOptions->CktEqpOptions)) {
foreach ($DesignLayoutRecord_value->cktEqpOptions->CktEqpOptions as $cv_obj)
{
if($cv_obj->attribute === 'CDR')
{
$this->cvCDRList[] = array("cdr" => $cv_obj->eqpValue);
}
if($cv_obj->attribute === 'CUSTOMER')
{
$this->cvCustomerList[] = array("customer" => $cv_obj->eqpValue);
}
if($cv_obj->attribute === 'LEASE LINE')
{
$this->cvphoneList[] = array("phoneNumber" => $cv_obj->eqpValue);
}
}
}
}
}
See how they are currently put into separate arrays like cvCDRList, cvCustomerList, and cvphoneList? How would I put them into a single array? Thanks!!
you can use array_merge.
<?php
$array1 = array("a12","a12","a13");
$array2 = array("a21","a22","a23");
$array3 = array("a31","a32","a33");
$finalArray = array_merge($array1,$array2,$array3);
foreach( $finalArray as $key => $value ){
echo $key."=>".$value."<br>";
}
?>
You can create another property called "allAtributes" .
When you finalize to fill your 3 arrays you can call to another method of class than make the merge between 3 array.
The finally you will have got like this :
allAtributes (array)=>{
["cdr"](array)=> {
['cdrkey1'] = cdrAtt1 ,
['cdrKey2'] = cdrAtt2 ...
},
["customer"](array)=> {
['customerkey1'] = customerAtt1 ,
['customerKey2'] = customerAtt2 ...
},
["phoneNumber"](array)=> {
['phoneNumberkey1'] = phoneNumberAtt1 ,
['phoneNumberKey2'] = phoneNumberAtt2 ...
}
}
You only must declare an array an add the other three arrays with the function array_merge into loops

PHP Can't get the right format for array

I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}

Categories