Three Dimensional Array Changing - php

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
}
}

Related

in_array() not working with two dimensional associative array?

I'm trying very simply to use in_array() to check a key is in an array and then echo its value.
$array = Array
(
[cart_item] => Array
(
[0] => Array
(
[product_name] => White Sakura Necktie
[id] => 11
[product_auto_id] => 556729685
[quantity] => 2
[product_regular_price] => 95
[product_sale_price] => 95
[product_image] => 556729680Black_Sakura_Necktie.jpg
)
[1] => Array
(
[product_name] => hhhad ba bhdbh
[id] => 10
[product_auto_id] => 951790801
[quantity] => 2
[product_regular_price] => 20
[product_sale_price] =>
[product_image] => 951790801hhhad_ba_bhdbh_.jpg
)
)
)
And I have value 556729685 which I want to check that this value exists or not? So I am using in_array() function for this.
in_array(556729685, array_keys($array));
in_array(556729685, array_values($array));
in_array(556729685, $array);
All above three i have used but result always showing NULL means blank.
I am really frustrated to find the solution. I don't understand what's happening.
You should use array_column() which will return the values from a single column in the input array as an array.
$product_auto_ids = array_column($array['cart_item'], 'product_auto_id');
In this case, it would return the following:
Array
(
[0] => 556729685
[1] => 951790801
)
Then you can use in_array() like you currently are.
in_array(556729685, $product_auto_ids);

php access array by key value

I have a JSON array which Im trying to parse with PHP using array_column (PHP 5.5).
My objective is to check the value of a particular key in the array and execute some additional code dependent on the result.
For example with the array below...I would like to find field_number 335 in the array and take the value (Last name) and echo to the screen. The actual array [1] could be different each time as the array grows, where as field_number would always be 335.
Array
(
[0] => Array
(
[id] => 286
[lead_id] => 5
[form_id] => 4
[field_number] => 1
[value] => First Name
)
[1] => Array
(
[id] => 287
[lead_id] => 5
[form_id] => 4
[field_number] => 335
[value] => Last name
)
[2] => Array
(
[id] => 288
[lead_id] => 5
[form_id] => 4
[field_number] => 339
[value] => Australia
)
Hopefully that makes sense and with enough information to help someone point me in the right direction.
Many thanks all!
Cheers
you can use array_search && array_column
$key = array_search('335', array_column($array, 'field_number'));
this should give you array id
eg. echo $array[$key]['value'];

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.

Issue getting info out of array

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'].

CakePHP Model index array needed, but can't generate from for loop counter. Need model indexed array for this to work

I am working on a function that submits multiple records on various relationship types. The main issue I am running into is the format of the array. In order for my saveAll() to work on my multiple relationships setup, the array needs to be in this format as you can see the models are Keys (first array below).
My main question is: 1) Is it possible to strip the numerical indexes off the second layer of the second array below?
I am returning my input fields like so. You can see the prefixed counter (which I believe is what is creating the numeric index on that second level).
<?php echo $this->Form->input("$i.monthly_cost", array('label' => 'Monthly Cost')); ?>
I am using a for loop counter for the fields. So my question number to is: can this for value be changed to something that will work with Cake's saveAll()?
<?php for ($i = 1; $i <= 2; $i++) { ?>
Example where models are the keys (this is the format I need):
Array
(
[User] => Array
(
[username] => billy
)
[Profile] => Array
(
[sex] => Male
[occupation] => Programmer
)
The only output I can get on my multiple input array (below is the debug() dump)
My actual output is numerically indexed:
Array
(
[Plan] => Array
(
[1] => Array
(
[plan_detail_id] => 36
[monthly_cost] => 0
[dental_cost] => 0
[age_id] => 14
[applicant_id] => 1
[state_id] => 1
)
[2] => Array
(
[plan_detail_id] => 36
[monthly_cost] => 0
[dental_cost] => 0
[age_id] => 2
[applicant_id] => 4
[state_id] => 1
)
)
[1] => Array
(
[1] => Array
(
[Zip] => Array
(
[0] => 487
[1] => 486
[2] => 485
[3] => 484
[4] => 483
)
)
)
[2] => Array
(
[2] => Array
(
[Zip] => Array
(
[0] => 485
[1] => 484
[2] => 483
)
)
)
)
Did you already check out the Set Core Utility Library? This can help you out a lot with array management.

Categories