Laravel check an array of object which contain in another array - php

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);

Related

Merge multiple object in foreach

I have one or more object in foreach and I want to merge all the objects in one in $refJSON.
$refObj = (object) array();
foreach($items as $item) { //here Im looping Two items
$refObj->refId = $item->getId();
$refObj->refLastName = $item->getLastName();
$refObj->refPhone = $item->getPhone();
$orderObj->refEmail = $item->getEmail();
}
$refJSON = json_encode($orderObj);
var_dump($refJSON);
Output :
//just the last item object
string(92) "{
"refId":"2",
"refLastName":"Joe",
"refPhone":"xxxxxxx",
"refEmail":"example#domaine.com"
}"
The output expected is to merge all the items ids 1 and 2 something like this:
[
{
"refId":"1",
"refLastName":"Steve",
"refPhone":"xxxxxxx",
"refEmail":"foo#domaine.com"
},
{
"refId":"2",
"refLastName":"Joe",
"refPhone":"xxxxxxx",
"refEmail":"example#domaine.com"
}
]
You are just overwriting the same object each time. Build each object and add this to an array (using []) and encode the result...
$refOut = array();
foreach($items as $item) { //here Im looping Two items
$refOut[] = ['refId' => $item->getId(),
'refLastName' => $item->getLastName(),
'refPhone' => $item->getPhone(),
'refEmail' => $item->getEmail()];
}
$refJSON = json_encode($refOut);

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

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'];
}
}
}

Creating new JSON by reading distinct JSON array elements in PHP

I have a JSON object that looks something like this
OBJECT $deals
[
{
"deal_id": 124563
"merchant_id": 123
"merchant_name": Merchant1
}
{
"deal_id": 456789
"merchant_id": 123
"merchant_name": Merchant1
}
{
"deal_id": 46646
"merchant_id": 456
"merchant_name": Merchant2
}
]
What I am trying to do is this right now
$category_merchants = array();
foreach ($deals as $deal) {
array_push($category_merchants, $deal->merchant_id, $deal->merchant_name)
}
$category_merchants = json_encode($category_merchants);
The new JSON object has all the merchants from the original JSON. Is there an easy way to just get the distinct merchants (merchant_name, merchant_id) in the new JSON with counts of how many times they were in the original JSON?
use array_map() like this:
array_map(function($v){return [$v->merchant_id, $v->merchant_name];}, $array);
Convert json to array
$array = json_decode($deals);
loop array to get unique merchant name
foreach($array as $key => $value) {
$category_merchants[$value['merchant_id']] = $value['merchant_name'];
$category_merchant_count[] = $value['merchant_id']; //this is to count number of merchant occurance
}
Convert category_merchants back to json
$merchant = json_encode($category_merchants);
Get number of merchant occurance
print_r(array_count_values($category_merchant_count))
One way. Just use the merchant_id as the key and increment the count:
$deals = json_decode($json, true);
foreach ($deals as $deal) {
if(!isset($category_merchants[$deal['merchant_id']])) {
$category_merchants[$deal['merchant_id']] = $deal;
$category_merchants[$deal['merchant_id']]['count'] = 1;
unset($category_merchants[$deal['merchant_id']]['deal_id']);
} else {
$category_merchants[$deal['merchant_id']]['count']++;
}
}
If you need to re-index the array then:
$category_merchants = array_values($category_merchants);

Build multidimensional array from keys

I can't seem to figure this out and I'm hoping someone has a magical recursive solution to this. I have a list of keys and basically I want to transform it into a nested array.
array('level1', 'level2', 'level3');
To
array(
'level1' => array(
'level2' => array(
'level3' // last key in array should be just a value
)
)
)
Much appreciation to anyone who can help!
Something like this should do the job:
function buildMultiDimensional(Array $arr)
{
// the first value will become a new key
$newKey = array_shift($arr);
if (empty($arr)) {
// this is where the recursion stops
return $newKey;
}
// and the recursion !!!
return array($newKey => buildMultiDimensional($arr));
}
$arr = array('level1', 'level2', 'level3', 'level4', 'level5');
var_dump(buildMultiDimensional($arr));
The result is what's expected:
array(1) {
["level1"]=>
array(1) {
["level2"]=>
array(1) {
["level3"]=>
array(1) {
["level4"]=>
string(6) "level5"
}
}
}
}
You don't need recursion. A single loop is fine with references.
<?php
//array to iterate
$array = array('level1', 'level2', 'level3');
//contains our entire array
$out = array();
//temp variable to store references as we go down.
$tmp = &$out;
//get the last value off the array
$last = array_pop($array);
//loop over the array
foreach($array as $level){
//make an array under the current level
$tmp[$level] = array();
//assign tmp to the new level
$tmp = &$tmp[$level];
}
//assign the last key as the value under the last key
$tmp = $last;
//display output
print_r($out);
example: http://codepad.viper-7.com/zATfyo
And without references, working in reverse:
<?php
//array to iterate
$array = array('level1', 'level2', 'level3');
//get the last value off the array
$out = array_pop($array);
//flip the array backwards
$array = array_reverse($array);
//loop over the array
foreach($array as $level){
$out = array($level=>$out);
}
//display output
print_r($out);
Example: http://codepad.viper-7.com/fgxeHO

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