Issue getting info out of array - php

I'm trying to get info out of this information:
Array (
[result] => success
[totalresults] => 1
[startnumber] => 0
[numreturned] => 1
[tickets] => Array (
[ticket] => Array (
[0] => Array (
[id] => 7
[tid] => 782755
[deptid] => 1
[userid] => 39
[name] => Mark Lønquist
[email] => mark.loenquist#outlook.com
[cc] =>
[c] => 79rzVBeJ
[date] => 2013-04-25 16:14:24
[subject] => test
[status] => Open
[priority] => Medium
[admin] =>
[attachment] =>
[lastreply] => 2013-04-25 16:14:24
[flag] => 0
[service] =>
)
)
)
)
The results are printed using:
print_r($results);
Usually, I've been able to do a simple:
$var = $results['something'];
To get it out, but it wont work with this :( Any help is appreciated.

After reformatting the array you pasted, it becomes clear that some elements are nested several levels deep. (It's a "multidimensional array"; see example #6 in the docs.) In those cases, you have to add additional brackets containing each successive key to reach the depth you want. For example, a sample from your $results array:
Array (
[result] => success
[totalresults] => 1
...
[tickets] => Array (
[ticket] => Array (
[0] => Array (
[id] => 7
[tid] => 782755
...
)
)
)
)
You simply need to do $results['totalresults'] to access "totalresults", but to get "tid" you would need to use $results['tickets']['ticket'][0]['tid'].
If you want to get "tid" from all of the tickets when there are multiple, you will have to iterate (loop) over the array of tickets. Probably something like this (untested, but should be close enough for you to figure out):
foreach ($results['tickets']['ticket'] as $ticket) {
echo $ticket['tid'];
}

To see what the problem is with your print_r() you may add error_reporting(E_ALL); to the top of your code.
Note that if you want to retrieve the value for a key such as 'totalresults' then $results['totalresults'] would be sufficient.
However, if you want to get a key from one of the nested arrays such as email then you would have to use $results['result']['tickets']['ticket'][0]['email'].

Related

Getting out the value of a key in multidimentional array in php

In my php query I got this output:
{"projects":[{"id":127,"name":"efrat","status":{"id":10,"name":"development","label":"development"},"description":"","enabled":true,"view_state":{"id":10,"name":"public","label":"public"},"access_level":{"id":90,"name":"administrator","label":"administrator"},"custom_fields":[{"id":1,"name":"Customer email","type":"email","default_value":"","possible_values":"","valid_regexp":"","length_min":0,"length_max":50,"access_level_r":{"id":10,"name":"viewer","label":"viewer"},"access_level_rw":{"id":10,"name":"viewer","label":"viewer"},"display_report":true,"display_update":true,"display_resolved":true,"display_closed":true,"require_report":false,"require_update":false,"require_resolved":false,"require_closed":false}],"versions":[],"categories":[{"id":93,"name":"Monitor","project":{"id":0,"name":null}},{"id":31,"name":"Proactive","project":{"id":0,"name":null}},{"id":30,"name":"Project","project":{"id":0,"name":null}},{"id":29,"name":"Support","project":{"id":0,"name":null}}]}]}
after using 'json_decode' method on it, I get this:
"(
[projects] => Array
(
[0] => Array
(
[id] => 127
[name] => myprojectname
[status] => Array
(
[id] => 10
[name] => development
[label] => development
)
[description] =>
[enabled] => 1
[view_state] => Array
(
[id] => 10
[name] => public
[label] => public
)
[access_level] => Array
(
[id] => 90
[name] => administrator
[label] => administrator
)
[custom_fields] => Array
(
[0] => Array
(
[id] => 1
[name] => Customer email
[type] => email
[default_value] =>
[possible_values] =>
[valid_regexp] =>
[length_min] => 0
[length_max] => 50
[access_level_r] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[access_level_rw] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[display_report] => 1
[display_update] => 1
[display_resolved] => 1
[display_closed] => 1
[require_report] =>
[require_update] =>
[require_resolved] =>
[require_closed] =>
)
)
[versions] => Array
(
)
[categories] => Array
(
[0] => Array
(
[id] => 93
[name] => Monitor
[project] => Array
(
[id] => 0
[name] =>
)
)
[1] => Array
(
[id] => 31
[name] => Proactive
[project] => Array
(
[id] => 0
[name] =>
)
)
[2] => Array
(
[id] => 30
[name] => Project
[project] => Array
(
[id] => 0
[name] =>
)
)
[3] => Array
(
[id] => 29
[name] => Support
[project] => Array
(
[id] => 0
[name] =>
)
)
)
)
)
)"
In my PHP, how can I release the "name" object value (the result should be 'myprojectname') from this array? I've tried many foreach loops that got me nowhere.
Thank you,
It looks like you have one object, that when decoded actually only has one array item. So, in your case, ‘myprojectname’ may simply be “$projects[0][‘name’]”
If many array items, you could
foreach ($projects as $project) {
echo $project[‘name’];
}
EDIT: I took object provided and json_decoded it myself, it doesn't match the json_decoded item presented by OP -- the first image shows the code to var_dump 'name' OP desired, part of the code also below:
$decoded = json_decode($obj);
$projects = $decoded->projects;
$name = $projects[0]->name;
Your 'projects' contains an array ("projects":[{"id":127, ... }]). I assume that the 'projects'-array might contain multiple 'project'-objects like this?
{
"projects":
[
{
"id":127,
"name":"my-project"
},
{
"id":128,
"name":"my-other-project"
}
]
}
In that case you need the arrow notation to access the name property, for example:
foreach ($projects as $project_object) {
foreach ($project_object as $project) {
echo $project->name . '<br/>';
}
}
EDIT:
I took a minimal code example of the OP and got the expected result:
Can you add more details in your code snippets in your original question or provide us with a working example of your code?
There are some online PHP sandboxes that can help you with this. For example: I stripped out all code that does not seem related to your question and got the result you are looking for in two different ways:
http://sandbox.onlinephpfunctions.com/code/009c53671fd9545e4fcecfe4b0328974381ee2ce
It is also a good idea to sum up all the foreach loops that you already tried, so we can see if you were nearly there with your own solution. This way we can understand your question better and it prevents us from offering solutions that you already used.

Three Dimensional Array Changing

I'm calling an three dimension array from an API, however after different calls to the API the data back is slightly different, sometimes the array keys change. For example the first array may relate to type one in one case, whereas in another case it relates to type two. It's laid out like this
Array
(
[id] =>
[stats] => Array
(
[0] => Array
(
[type] =>
[option] =>
[modifyDate] =>
As stated before sometimes it relates to different types, is there a way of getting an array based on what is inside of it, for example if the "type" in the first array equals type one then assign that to the variable Type1?
Perhaps in a better example, in scenario 1 it shows this:
Array
(
[summonerId] => 39562006
[playerStatSummaries] => Array
(
[0] => Array
(
[playerStatSummaryType] => AramUnranked5x5
[wins] => 4
[modifyDate] => 1481110651000
[aggregatedStats] => Array
(
[totalChampionKills] => 48
[totalTurretsKilled] => 2
[totalAssists] => 171
)
)
whereas in scenario 2 it shows this
Array
(
[summonerId] => 34951469
[playerStatSummaries] => Array
(
[0] => Array
(
[playerStatSummaryType] => CAP5x5
[wins] => 16
[modifyDate] => 1481117277000
[aggregatedStats] => Array
(
[totalChampionKills] => 325
[totalMinionKills] => 1996
[totalTurretsKilled] => 26
[totalNeutralMinionsKilled] => 1048
[totalAssists] => 298
)
)
After some trial and error myself i think a foreloop will be good as it could iterate each array and output chosen keys from the array however i'm still unsure on how to do this, any suggestions?
My advice is similar to this answer: https://stackoverflow.com/a/42708457/2943403
Unfortunately, I cannot give more detailed information without small relevant samples of the related input arrays and a desired output array.
// $new=array(...);
// $old=array(...);
foreach($new as $new_key=>$new_subarray){
foreach(array_diff_key($old,range(0,$new_key)) as $old_subarray){ // no dupe loops
// perform checks between $new_subarray and $old_subarray
}
}

Complicated PHP transpose / pivot

I have the following array :
Array
(
[0] => Array
(
[Name] => first_data
[building] => A
[apt] => 16
)
[1] => Array
(
[Name] => first_data
[building] => B
[apt] => 16
)
[2] => Array
(
[Name] => second_data
[building] => A
[apt] => 17
)
[3] => Array
(
[Name] => second_data
[building] => B
[apt] => 18
)
and I need it to be returned as :
Array
(
[0] => Array
(
[Name] => first_data
[A] => 16
[B] => 16
)
[1] => Array
(
[Name] => second_data
[A] => 17
[B] => 18
)
Any ideas?
BTW the first array has hundreds of entries (not only first_data, but second and etc...) plus it has more than A and B.
Thanks in advance.
Not exactly what you want, but if you instead index the new array by the name, you can do this very easily. If the index number is some kind of ID, you can just create a field for it
foreach ( $oldarray as $index => $piece )
{
$newarray[$piece['Name']] = array($piece['building'] => $piece['apt'])
}
This will give you
Array
(
['first_data'] => Array
(
['A'] => 16,
['B'] => 16
)
['second_data'] => Array
(
['A'] => 17,
['B'] => 18
)
)
Since you have two entries with the same new, when you hit the 2nd loop, it will simply add the other building name. If you can work with this layout, then your solution is very easy, it will take more steps to do it exactly as you showed. If you absolutely have to do it the way you showed, you need extra code to loop through the new array, find the building name, add the key in the correct place, but this will be slower if you have a large amount of data.
In my opinion, the way I presented it is a far easier way to look around the array too. If you wanted to know the apt value for A in "second_data" you can just do
$newarray['second_data']['A']
with your array layout, it would require a loop to search the array for "second_data" because you have no idea where it is.

PHP: Accessing child arrays when you don't know the parent's keys and you can't just search for the value needed

I have a PHP array containing movie descriptions ($descriptions) and another PHP array containing showtimes and ticket quantities ($stock) for those movies. For each unique movie ID in $descripctions, I need to get all of the showtimes and tickets from $stock.
Is there no built-in PHP function that will search for the unique ID and return the chain of keys needed to access that value? I can't find an elegant solution after a full day of Googling and reviewing every array function in the PHP manual twice.
If there's no more elegant solution, is my best approach a custom recursive function? If so, any guidance on best approach / control structure? Maybe counting array elements and using several levels of while loops to go through each level of the array?
Here's the beginning of the $stock array I'm trying to get the data from -- won't post the entire print_r() because the source array is over 67,000 lines long but this much should indicate the structure I'm working with.
Thank you very much!!!
Array (
[products] => Array (
[venue] => Array (
[0] => Array (
[title] => 3-D Digital Cinema
[length] => 25
[memberonly] => 0
[shows] => Array (
[show] => Array (
[0] => Array (
[title] => Planet You
[location] => 3-D Digital Cinema
[eventnumber] => 521
[date] => Array (
[0] => Array (
[eventdate] => 2012/01/01
[times] => Array (
[time] => Array (
[0] => Array (
[starttime] => 13:00:00
[instock] => 110
)
[1] => Array (
[starttime] => 16:00:00
[instock] => 110
)
)
)
)
[1] => Array (
[eventdate] => 2012/01/02
[times] => Array (
[time] => Array (
[0] => Array (
[starttime] => 13:00:00
[instock] => 110
)
[1] => Array (
[starttime] => 16:00:00
[instock] => 110
)
)
)
)

Manipulating arrays in php

I have an file uploading site, it has an option of uploading through urls, what I am trying to do is whenever a user uploads through url, I check my database if a file exists that was uploaded through same url it displays the download url directly instead of uploading it again.
The data sent to uploading script is in array form like:
Array (
[0] => http://i41.tinypic.com/3342r93.jpg
[1] => http://i41.tinypic.com/28cfub7.jpg
[2] => http://i41.tinypic.com/12dsa32.jpg
)
and the array used for outputing the results is in form like this:
Array
(
[0] => Array
(
[id] => 43
[name] => 3342r93.jpg
[size] => 362750
[descr] =>
[password] =>
[delete_id] => 75CE
[upload_id] => 75F45CAE1
)
[1] => Array
(
[id] => 44
[name] => 28cfub7.jpg
[size] => 105544
[descr] =>
[password] =>
[delete_id] => D392
[upload_id] => 6676FD881
)
[2] => Array
(
[id] => 45
[name] => 12dsa32.jpg
[size] => 49000
[descr] =>
[password] =>
[delete_id] => 54C9
[upload_id] => A58614C01
)
)
Now I want is that if the link http://i41.tinypic.com/28cfub7.jpg is already upload I just add it to output array but maintain it in a order (if the link added was 2nd in array the output result should also show it in 2nd)
So what function should be used to remove the matched urls from input array and a function to add it output array in the order no.
// edited
Yes unset will do the thing but I want to maintain the order:
For example after unsetting the array looks like this:
Array (
[0] => http://i41.tinypic.com/3342r93.jpg
// [1] was removed
[2] => http://i41.tinypic.com/12dsa32.jpg
)
but the output array would be
Array
(
[0] => Array
(
[id] => 43
[name] => 3342r93.jpg
[size] => 362750
[descr] =>
[password] =>
[delete_id] => 75CE
[upload_id] => 75F45CAE1
)
// this will become [1], so how can i add another output[1] and shift other
// items after it to [2], [3] and so on...
[1] => Array
(
[id] => 45
[name] => 12dsa32.jpg
[size] => 49000
[descr] =>
[password] =>
[delete_id] => 54C9
[upload_id] => A58614C01
)
)
Well, you can add it to the output array by doing something like:
$OutArray[2] = $element;
Where $element is another Array with the id, name, size (etc...) elements.
As for removing from the array:
unset($OutArray[2]);
You may want to read Array (PHP manual).
If you have an indexed array, you can remove a value by doing:
unset ($array[2]);
If you want to add an item to an array, use this shorthand of array_push (you don't need to specify an index!):
$array[] = "new object";
All documentation is on php.net/arrays
Why don't use an if statement and/or file_exists() to see if the file is there. If you already have an array with the values then it just won't be uploaded again.

Categories