Merge multiple object in foreach - php

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

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

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

How do I get the commun results in a for loop in a unknown array length PHP

I have a array of dates, I would like to get all values that are in all of them, thats my example:
$array = [
{"d1":["2016-01-04","2016-01-11","2016-01-18","2016-01-25","2016-02-01"]},
{"d2":["2016-01-05","2016-01-11","2016-01-19","2016-01-25","2015-12-12"]},
{"d3":["2016-01-05","2016-01-11","2016-01-25"]},
{"d4":["2016-01-04","2016-01-11","2016-01-25"]}
]
As result:
$result = ["2016-01-11", ,"2016-01-25"];
Here is a working example (can be optimized, but it should work):
$array = json_decode('[
{"d1":["2016-01-04","2016-01-11","2016-01-18","2016-01-25","2016-02-01"]},
{"d2":["2016-01-05","2016-01-11","2016-01-19","2016-01-25","2015-12-12"]},
{"d3":["2016-01-05","2016-01-11","2016-01-25"]},
{"d4":["2016-01-04","2016-01-11","2016-01-25"]}
]');
$allArrays = array();
foreach ($array as $object) {
foreach ($object as $datesArray) {
array_push($allArrays, $datesArray);
}
}
$sharedDates = call_user_func_array('array_intersect',$allArrays);
var_dump($sharedDates);

Arrays from Twitter json

I am trying to convert json feed from Twitter API 1.1 to arrays. What I am trying is
foreach($user))
Main_Array{
Name:
Id:
Array{
Array {
Tweet:
created at:
}
Array {
Tweet:
created at:
}
}
}
}
var_dump(Main_Array()); //unable to get the main array here. Only the last element of array is pulled
Here is what I tried:
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$user."&count=".$notweets);
$status = array();
foreach($tweets as $key) {
$status['text'] = $key ->text;
$status['stamp'] = $key -> created_at;
}
$tweetfeed = array (
'name' => $name,
'id' => $tweetname,
'status' => $status
);
I am only getting the last value for status array.
Also, I want to know if the structure I am using is good or please suggest if this can be better.
Thanks in advance.
You overwrite the previous $status entries every time in your foreach loop. You've to create a new sub-array for each tweet.
Here is a way to do it :
$i = 0;
foreach($tweets as $key) {
$status[$i]['text'] = $key ->text;
$status[$i]['stamp'] = $key -> created_at;
++$i;
}

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