Exclude items from JSON string that is generated from PHP Array - php

I have a PHP function $users->getFullUserList('json') that returns a JSON string holding a Userlist of user data which is built from a PHP Array using PHP's json_encode($this->userListArray)
The PHP Array $this->userListArray looks something like this below before being converted into a JSON string...
Array
(
[user1] => Array
(
[id] => 1
[user_name] => jasondavis
[first_name] => Jason
[last_name] => Davis
[is_admin] => 1
[email_address] => jasonyrty#tyrtl.com
[gravatar_id] => 31b64e4876d603ce78e04102c67d6144
)
[1702c3d0-df12-2d1b-d964-521becb5e3ad] => Array
(
[id] => 1702c3d0-df12-2d1b-d964-521becb5e3ad
[user_name] => Jeff
[first_name] => Jeff
[last_name] => Mosley
[is_admin] => 1
[email_address] => fgfgh#rtyrtyre.com
[gravatar_id] => 5359bf585d11c5c35602f9bf5e66fa5e
)
)
What I need help with is making my function $users->getFullUserList('json') to allow another parameter to be injected which will be an array of keys which should NOT be part of the final JSON String
For example if I want to generate my JSON string from the PHP Array and have it exclude user email_address and first_name keys from the JSON string.
I do not want to simply remove them from the PHP Array as I will need access to them in PHP later on. I just want the keys in my new passed in array to be excluded from the generated JSON and still remain in the PHP Array.
$excludeKeysFromJson = array(
'first_name',
'email_address'
);
$users->getFullUserList('json', $excludeKeysFromJson)
I realize the simple solution would be to clone my $this->userListArray Array and then remove the matching keys from the $excludeKeysFromJson Array and generate the JSON string from the new cloned Array.
I am hoping to find a better performance method that doesn't require cloning my huge userlist array and keeping 2 copies of the userlist array with 1 missing a couple keys.
Is there a better way?

You can create an array with keys filtered out using array_diff_key and array_flip (to turn the exclusion array values into keys)
Something like this...
public function getFullUserList($format, array $exclude = []) {
$filtered = array_map(function($user) use ($exclude) {
return array_diff_key($user, array_flip($exclude));
}, $this->userListArray);
switch($format) {
case 'json' :
return json_encode($filtered);
default :
return $filtered;
}
}
Demo

Related

combine multi-dimensional array on value from JSON

I have 2 api end points that load JSON data...
1. subject matter experts
Array
(
[0] => Array
(
[ExpertiseId] => 1
[IndustryId] => 1
[PersonId] => 3
)
...
)
people database
Array
(
[0] => Array
(
[Id] => 1
[Name] => Joe
[Office] => New York
)
....
)
I'd like to pass both functions into an array, specify to merge on [matter.PersonId] => [people.Id] so the returned array would become
Array
(
[0] => Array
(
[ExpertiseId] => 1
[IndustryId] => 1
[PersonId] => 3
[Id] => 1
[Name] => Joe
[Office] => New York
)
...
)
You have to iterate over both arrays and reorganize the data in such a way that merging can happen. In practice that means rekeying the first array by PersonId and the second by Id; this is very easy to do with array_column:
$matter = array_column($matter, null, 'PersonId');
$people = array_column($people, null, 'Id');
At this point only a simple task is left: merging the items (arrays) that share the same key in both $matter and $people.
In a perfect world that would be an one-liner with array_merge_recursive, but that function does not actually merge arrays that have integer keys like these (the ids we used as keys are integers). So a little standard iteration is in order: pick one of the arrays and merge its contents with the other:
foreach ($people as $id => $data) {
// If there's a guarantee that both arrays will definitely have the same
// set of keys (ids) so that $matter[$id] is guaranteed to exist,
// you can also use the simpler: $matter[$id] += $data
$matter[$id] = isset($matter[id]) ? $matter[$id] + $data : $data;
}
...and now $matter has all the data merged together.
Try array_merge()
$newArray = array_merge(first_array, second_array);

Getting Array Data

The following is a profile array printed using r_print:
Array
(
[0] => Array
(
[Title] => Profile
[Name] => Veritas
[NKey] => Key_1
[SKey] => Key_2
)
[1] => Array
(
[Title] => Access
[Admin] => True
[Banned] => False
[Public] => True
)
)
What I'm trying to do, is simply retrieve elements of that array.
IE,
$profile[] = ...; //GET_ARRAY
$user = $profile[0]['Name'];
$key_1 = $profile[0]['NKey'];
$key_2 = $profile[0]['SKey'];
$admin = $profile[1]['Admin'];
For some reason, the above code doesn't work, though logically it should work without a problem.
What IS returned, is just the character 'A' if I target anything within the array.
You are adding another level to your array by assigning the array to $profile[]. The brackets turn $profile into an array and then adds that array to it causing the extra level.
$profile[] = ...; //GET_ARRAY
should just be
$profile = ...; //GET_ARRAY
Figured out what I was looking for, thought PHP automatically formated arrays (string data) passed from another page. I solved my issue using serialize() & unserialize().

php convert a string into multi dimensional array

I have seen many posts on here about converting a multi dimensional array into a string but not the other way around so I have a question to ask. I have got the following string of data which is retrieved from a JQuery array via a post:
["enquiry#gardengamesltd.co.uk, sales#gardengamesltd.co.uk","http://www.gardengamesltd.co.uk/acatalog/contactus.html"],["enquiry#gardengames.com","http://www.gardengames.com/contact/"],["info#gardengamesandleisure.com","http://www.gardengamesandleisure.com/ContactUs.aspx"],["playtime#kentgardengameshire.com","http://www.kentgardengameshire.com/contact-us.html"],["sales#gardengamesuk.com","http://www.gardengamesuk.com/contact.php"],["team#gardenknightgames.com","http://www.gardenknightgames.com/contact/"],["ajax-loader#2x.gif","http://www.just-garden-games.co.uk/"]
What I am wanting to do is convert it into an array which looks like so:
Array
(
[0] => Array
(
[Email] => enquiry#gardengamesltd.co.uk, sales#gardengamesltd.co.uk
[FB] => http://www.gardengamesltd.co.uk/acatalog/contactus.html
)
[1] => Array
(
[Email] => enquiry#gardengames.com
[FB] => http://www.gardengames.com/contact/
)
[2] => Array
(
[Email] => info#aaeventhire.com
[FB] => http://www.aaeventhire.com/pricing/garden-games
)
)
I realize I could use $array = explode('","', $harvest_data); however this is only going to give me a single level array and ideally I am wanting to keep email, fb inside an inner array.
Has anyone got any ideas on how I can go about doing this?
Thanks.
As it is, your string is not valid JSON. Wrapping it in a pair of []'s would work in this case so if the input always has this form, this would work:
$json_string = '[' . $your_string . ']';
$your_array = json_decode($json_string);
However, it would be best to make sure that your front-end / javascript posts valid JSON to begin with.
Working example.

Navigating a multidimensional array with dynamic

I'm trying to figure out why it is that I cannot access the follow array with this statement:
var_dump($thevar[0]['product_id']);
Array
(
[d142d425a5487967a914b6579428d64b] => Array
(
[product_id] => 253
[variation_id] =>
[variation] =>
[quantity] => 1
[data] => WC_Product Object
(
[id] => 253
[product_custom_fields] => Array
(
[_edit_last] => Array
(
[0] => 1
)
[_edit_lock] => Array
(
[0] => 1345655854:1
)
[_thumbnail_id] => Array
(
[0] => 102
)
I can, however, access the 'product_id' using the dynamically created array name:
print_r($thevar['d142d425a5487967a914b6579428d64b']['product_id']);
The issue is, I don't know what that dynamic name is going to be on the fly...
There are several options for such scenarios.
Manually iterate over the array
You can use reset, next, key and/or each to iterate over the array (perhaps partially).
For example, to grab the first item regardless of key:
$item = reset($thevar);
Reindex the array
Sometimes it's just convenient to be able to index into the array numerically, and a small performance hit is not a problem. In that case you can reindex using array_values:
$values = array_values($thevar);
$item = $values[0]; // because $values is numerically indexed
Iterate with foreach
This would work for a single value as well as it works for more, but it might give the wrong impression to readers of the code.
foreach($thevar as $item) {
// do something with $item
}
If the array key is dynamic you might find the PHP function array_keys() useful.
It will return an array of the keys used in an array. You can then use this to access a particular element in the array.
See here for more:
http://php.net/manual/en/function.array-keys.php
Because PHP array are associative therefor you have to access them by key.
But you may use reset($thevar) to get first item.
Or array_values():
array_values($thevar)[0]
Or if you feel like overkill you may also use array_keys() and use the [0] element to address element like this:
$thevar[ array_keys($thevar)[0]]

Get key values from multidimensional array

I have a page that searches a database and generates the following array. I'd like to be able to loop through the array and pick out the value next assigned to the key "contact_id" and do something with it, but I have no idea how to get down to that level of the array.
The array is dynamically generated, so depending on what I search for the index numbers under "values" will change accordingly.
I'm thinking I have to do a foreach starting under values, but I don't know how to start a foreach at a sublevel of an array.
Array (
[is_error] => 0
[version] => 3
[count] => 2
[values] => Array (
[556053] => Array (
[contact_id] => 556053
[contact_type] => Individual
[first_name] => Brian
[last_name] => YYY
[contact_is_deleted] => 0
)
[596945] => Array (
[contact_id] => 596945
[contact_type] => Individual
[first_name] => Brian
[last_name] => XXX
[contact_is_deleted] => 0
)
)
)
I've looked at the following post, but it seems to only address the situation where the array indices are sequential.
Multidimensional array - how to get specific values from sub-array
Any ideas?
Brian
You are correct in your assumption. You could do something like this:
foreach($array['values'] as $key => $values) {
print $values['contact_id'];
}
That should demonstrate starting at a sub level. I would also add in your checks to see if its empty and if its an array... etc.
Another hint regarding syntax - if the array in your original example is called $a, then the values you want are here:
$a['values'][556053]['contact_id']
and here:
$a['values'][596945]['contact_id']
So if there's no additional structure in your array, then this loop is probably what you want:
foreach ($a['values'] as $toplevel_id => $record_data) {
print "for toplevel_id=[$toplevel_id], contact_id=[" . $record_data['contact_id'] . "]\n";
}
foreach($array['values'] as $sub_arr){
echo $sub_arr['contact_id'];
}

Categories