php access array by key value - php

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

Related

PHP/Guzzle Target parent element

I have an app using guzzle/php to make requests to a rest service.
When it yields a response, it includes nested arrays and objects:
[exampleBalances] => Array (
[0] => stdClass Object (
[balance] => 6
[name] => Prize One
[prizeCode] => 38
)
[1] => stdClass Object (
[balance] => 5
[name] => Prize Two
[prizeCode] => 20
)
[2] => stdClass Object (
[balance] => 4
[name] => Prize Four
[prizeCode] => 39
)
)
Until now Ive been pulling the value based on the order:
$prizeThree = $response->exampleBalances['3']->balance;
However, the service wont display any 'prizes' if the customer has 0, so the example above would no longer be accurate if a new item was added:
[exampleBalances] => Array (
[0] => stdClass Object (
[balance] => 6
[name] => Prize One
[prizeCode] => 38
)
[1] => stdClass Object (
[balance] => 5
[name] => Prize Two
[prizeCode] => 20
)
[2] => stdClass Object (
[balance] => 8
[name] => Prize Three
[prizeCode] => 54
)
[3] => stdClass Object (
[balance] => 4
[name] => Prize Four
[prizeCode] => 39
)
)
Is there a way to target the correct element, without using the order that it appears in the response?
I could not find any documentation, but its difficult to convey the issue. I was thinking there may be someway to create a condition to check an elements inner values (preferably the 'prize code') Any help would be greatly appreciated.
In PHP 5.5.0 or newer, you can use the array_column() function to do this search:
$index = array_search($prizeCodeSearch, array_column($exampleBalances, 'prizeCode'));
$element = $exampleBalances[$index];

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.

multi dimensional array in random order

I want to make it so that my multi dimensional array is in a random order. How would you do it?
// This is how the array looks like
print_r($slides);
Array
(
[0] => Array
(
[id] => 7
[status] => 1
[sortorder] => 0
[title] => Pants
)
[1] => Array
(
[id] => 8
[status] => 1
[sortorder] => 0
[title] => Jewels
)
[2] => Array
(
[id] => 9
[status] => 1
[sortorder] => 0
[title] => Birdhouse
)
[3] => Array
(
[id] => 10
[status] => 1
[sortorder] => 0
[title] => Shirt
)
[4] => Array
(
[id] => 11
[status] => 1
[sortorder] => 0
[title] => Phone
)
)
// This how the result is if I use array_rand()
print_r(array_rand($slides, 5));
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
// This how the result is if I use shuffle()
print_r(shuffle($slides));
1
shuffle() is the way to go here. It prints 1 because shuffle changes the array in-place and returns a boolean, as it is written in the documentation:
Returns TRUE on success or FALSE on failure.
I suggest to also read the documentation of array_rand():
Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.
Always read documentation if you use built-in functions. Don't just assume how the work. I bet it took more time to write the question than looking this up.
Instead of
print_r(shuffle($slides));
do
shuffle($slides);
print_r($slides);
You see shuffle() shuffles the array in-place
i am not sure how you want it to display but you can loop the array and use php rand(0,arraylen) function to parse the array.
It works perfect. print_r(shuffle($slides))) gives the output of TRUE, since the return value of shuffle is a boolean and not an array.
See the working example here: http://codepad.org/B5SlcjGf

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