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().
Related
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
So I am working with wordpress and using the following code I get the following. I know this must be a basic question but I want to know what it means:
[1012] => Array ( [0] => 1 )
[1013] => Array ( [0] => 0 )
[1014] => Array ( [0] => 0 )
[1018] => Array ( [0] => 0 )
PHP:
<?php
$all_meta_for_user = get_user_meta(get_current_user_id());
print_r( $all_meta_for_user );
?>
This data is user's metadata https://codex.wordpress.org/Function_Reference/get_user_meta
As you say, this is your metadata. Two things here: first of all, I'll store all that data together inside a single key and I'll remove the uneeded single-element array:
[my_plugin] => Array( [1012] => 1, [1013] => 0 ...)
That lowers the possibility of your data mixing with other's plugin data, having conflicts, etc. Also, as second array is probably not needed, it will make access to it a little simpler.
When you have that, it's only a matter of accessing the value like this:
if ($all_meta_for_user['my_plugin'][$id] == 1) show_the_post()
where $id is the post ID.
To use a single key, I'll do something like this (untested):
$posts_meta_for_user = get_user_meta(get_current_user_id(), 'my_plugin', true);
if (is_array($posts_meta_for_user)) {
$posts_meta_for_user[$new_id] = $new_value;
update_user_meta(get_current_user_id(), 'my_plugin', $posts_meta_for_user);
} else {
$posts_meta_for_user = array($new_id => $new_value);
add_user_meta(get_current_user_id(), 'my_plugin', $awesome_level);
}
Notice that we get only the meta value named 'my_plugin' and test it already had a value by checking that is an array. If it is, we update it, and if it's not, we create a new one. $new_id is the post ID you want to store and $new_value the value.
I've searched a lot for this, and found several similar questions, but none quite address what I'm trying to accomplish.
I'm trying to write a code that will search a PHP (multi)multidimensional array to see which subarray contains the unique key value that I have. Then I would like it to return the value of a different key in that same object subarray.
$Arraytosearch = Array(
.
//various other subarrays
.
[fields] => Array (
.
.
.
//I don't know the number of the object subarray
[x] => PodioTextItemField Object (
[__attributes] => Array (
[field_id] => 37325091
[type] => text
[external_id] => id
[label] => ID
[values] => Array (
[0] => Array (
[value] => REF100019 ) )
[config] => Array (
[description] => [settings] => Array (
[size] => small )
[required] => [mapping] => [label] => ID [visible] => 1 [delta] => 2 ) )
.
.
.
//(and so on)
I'd like to write a function that will return "REF100019" by supplying the value of the field_id => 37325091.
Some things I have tried that I couldn't get to work:
foreach
and new RecursiveIterator although the tutorials I read weren't useful for my case here.
Even though the array looks complicated, I think it will be easy since I already have the field id of the parent array.
Thank you in advance for any guidance or sample codes that will work!
Background: This is a part of the response I get from Podio after submitting a request to their API. I just don't know how to take that response and get the piece I need (the ID) so that I can echo it for users).
EDIT: Thank you Orangepill and Barmar for the support. I tried your code. But was getting an error, which made me realize I hadn't given you the full array. I figured out how to get the Podio response to display in a more readable format (I was reading the full JSON response before from the Podio debug file which was super confusing), and figured out the full array is actually structured as I have shown below.
I then took your code and was able to figure out how to make it work for my scenario (see below). Very proud of myself considering I have never written any code before, but I couldn't have done it without your help! Thanks again!
$Arraytosearch = Array(
[items] => Array(
[0] => PodioItem Object(
[_attributes] => Array(
[fields] => Array (
[x] => PodioTextItemField Object (
[__attributes] => Array(
[field_id] => 37325091
[values] => Array(
[0] => Array(
[value] => REF100019 ) )
Note: For anyone who is new to programming like myself and wants the Podio response (or any JSON string) to display in a "pretty" readable format like above, use the code (from Display an array in a readable/hierarchical format thanks to Phenex):
print "<pre>";
print_r($Arraytoformat);
print "</pre>";
And finally, the full code I used (using Orangepill's answer below) which searches the objects and arrays and gives me what I have been searching for for days now is as follows:
$Arraytosearch = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["items"][0]->__attributes["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitem->__attributes["values"][0]["value"];
}}}
$refID = getFirstValueByFieldId($fieldID, $Arraytosearch);
The podio-php library has built-in methods that handle all this for you. There's no need to mess with the __attributes property yourself.
You can see a bunch of examples at https://github.com/podio/podio-php/blob/master/examples/items.php
In your case:
// Get item collection
$itemCollection = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
foreach ($itemCollection['items'] as $item) {
// Get the field from the item
$field = $item->field($fieldID);
// Now you can print the value of that field
print $field->humanized_value;
// Or if you don't want to have the content sanitized:
print $field->values[0]['value'];
}
There is a lot of ways to skin this cat... this is probably the most straight forward
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitems->__attributes["values"][0]["value"];
}
}
}
to Use in your case would be
echo getFirstValueByFieldId("37325091", $Arraytosearch);
Basically it walks the elements in the fields array and returns the value in the first associated value in the values array where field_id is equal to the parameter of the function.
Just a quick one i need to get a value from an array the array is made like this
$resultOfAdd[“CaseAndMatterResult”][“ResultInfo”][“ReturnCode”];
and it gives an output of this
Array (
[AddCaseAndMatterResult] => Array (
[ResultInfo] => Array (
[ReturnCode] => OK
[Errors] =>
[Warnings] =>
)
[CaseID] => 4880062
[MatterID] => 4950481
[LeadID] => 0
[CustomerID] => 0
)
)
All i want to do is put the part "MatterID" into a variable. how would I achieve this.
i have tried
$matterID = array($resultOfAdd["MatterID"]);
and this does not work
Regards
This is a multi-dimensional, associative array. Think of it like floors of a building. The key MatterID does not live in the first dimension (floor), rather on the second, in the AddCaseAndMatterResult sub-array.
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID']
Successive dimensions of an array are specified with successive square-brackets, each naming the key to look in (this is true of most languages).
$matterID = $yourArray['AddCaseAndMatterResult']['MatterID'];
Use this way:
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID'];
I'm a bit struggling with the associative arrays in associative arrays. Point is that I always have to drill deeper in an array and I just don't get this right.
$array['sections']['items'][] = array (
'ident' => $item->attributes()->ident,
'type' => $questionType,
'title' => $item->attributes()->title,
'objective' => (string) $item->objectives->material->mattext,
'question' => (string) $item->presentation->material->mattext,
'possibilities' => array (
// is this even neccesary to tell an empty array will come here??
//(string) $item->presentation->response_lid->render_choice->flow_label->response_label->attributes()->ident => (string) $item->presentation->response_lid->render_choice->flow_label->response_label->material->mattext
)
);
foreach ($item->presentation->response_lid->render_choice->children() as $flow_label) {
$array['sections']['items']['possibilities'][] = array (
(string) $flow_label->response_label->attributes()->ident => (string) $flow_label->response_label->material->mattext
);
}
So 'possibilities' => array() contains an array and if I put a value in it like the comment illustrates I get what I need. But an array contains multiple values so I am trying to put multiple values on the position $array['sections']['items']['possibilities'][]
But this outputs that the values are stores on a different level.
...
[items] => Array
(
[0] => Array
(
[ident] => SimpleXMLElement Object
(
[0] => QTIEDIT:SCQ:1000015312
)
[type] => SCQ
...
[possibilities] => Array
(
)
)
[possibilities] => Array
(
[0] => Array
(
[1000015317] => 500 bytes
)
[1] => Array
...
What am trying to accomplish is with my foreach code above is the first [possibilities] => Array is containing the information of the second. And of course that the second will disappear.
Your $array['sections']['items'] is an array of items, so you need to specify which item to add the possibilities to:
$array['sections']['items'][$i]['possibilities'][]
Where $i is a counter in your loop.
Right now you are appending the Arrays to [items]. But you want to append them to a child element of [items]:
You do:
$array['sections']['items']['possibilities'][] = ...
But it should be something like:
$array['sections']['items'][0]['possibilities'][] = ...
$array['sections']['items'] is an array of items, and as per the way you populate the possibilities key, each item will have it's own possibilities. So, to access the possibilities of the item that is being looped over, you need to specify which one from $array['sections']['items'] by passing the index as explained in the first answer.
OR
To make things simpler, you can try
Save the item array (RHS of the first =) to a separate variable instead of defining and appending to the main array at the same time.
Set the possibilities of that variable.
Append that variable to the main $array['sections']['items']
I have:
array[{IsChecked: true, SEC: 0, STP: 0},
{IsChecked: ture ,SEC: 0, STP: 1},
{IsChecked: false, SEC: 1 ,STP: 0}]
How to get each SEC where IsCheked value is true?