Dynamically finding a particular array index - php

I have a large multi-dimensional array with multiple occurrences of #options indexes. The following is a single array example:
FORM => Array
(
[#attached] => Array
(
[library] => quiz/quiz-form-styling
)
[text_0] => Array
(
[#type] => markup
[#markup] =>
Wherelese did Walter White work besides being a teacher?
)
[radio_1] => Array
(
[#type] => radios
[#options] => Array
(
[0] => An elder Care home
[1] => [A car wash]
[2] => A beauty saloon
[3] => For Skylers old boss
)
[#correct] => testing_correct_for radio
)
[text_2] => Array
(
[#type] => markup
[#markup] =>
)
)
In the example above, the parent array of #options is radio_1. But that is not always the case as the arrays are dynamically generated. There is no way to know in advance what the parent index would be but there is always an #options index.
What I'm trying to figure out is how to find and retrieve the data in all occurrences of #options. How can I do that?

I'd suggest iterating the set of form elements and checking if an inner #options key exists. If so, you can add the options to your array of all options.
$all_options = [];
foreach ($form_elements as $name => $settings) {
if (isset($settings['#options'])) {
$all_options[$name] = $settings['#options'];
}
}
I used the element name as key in the example code, because I thought it seemed like it would be convenient to know where the options came from, but you wouldn't have to do it that way. If you just wanted them all in one big list, you could merge them onto $all_options instead of appending them.
$all_options = array_merge($all_options, $settings['#options']);
This is assuming each of the values under FORM is an array representing one form element. If there is any nesting such that #options could appear at a deeper level, a recursive search could handle that, but if not, I think it's best to keep it simple.

You can try something like recursive function
Here is simple example for above case.
$alloptions = array();
function seach($searcharray){
foreach($searcharray as $key=>$value){
if($key == '#options'){
$alloptions[] = $searcharray[$key];
}else if(is_array($value)){
seach($value);
}
}
}

Related

PHP arrays within an array - nested arrays PHP

I'm using ACF Pro plugin for Wordpress and use repeater fields.
With this code I get all the field values and additional info in an array:
$fields = get_field_object('slideshow');
With this code I can narrow it down to what I want to achieve:
print_r($fields[value];
By now I get this array below:
Array
(
[0] => Array
(
[videoWebm] => /wc/data/uploads/sea.webm
[videoMp4] => /wc/data/uploads/sea1.mp4
[text] => Test1
[kund] => Kund1
[link1] =>
[link2] =>
)
[1] => Array
(
[videoWebm] => /wc/data/uploads/turntable.webm
[videoMp4] => /wc/data/uploads/turntable.mp4
[text] => Test2
[kund] => Kund2
[link1] =>
[link2] =>
)
)
it can grow more - like [2] => Array, [3] => Array etc.
I want to access all videoWebm & videoMp4 values.
As of now I know how to access a specific value - for example:
print_r($fields[value][0][videoWebm]);
But I can't figure out how to access all of them and put them in two new arrays. One for videoWebm values and one for videoMp4 values. The problem for me is the index value when I try to loop thru the array. I don't know if this really is the way to go...
Anyone suggestions?
Best, Niklas
You can use foreach:
foreach ($fields[value] as $field) {
$videoWebms[] = $field['videoWebm']
$videoMp4s[] = $field['videoMp4'];
}
Or as splash58 said, use array_column:
$vieoWebms = array_column($fields[value], 'videoWebm');
$vieoMp4s = array_column($fields[value], 'videoMp4');
I would highly recommend you learn about php's foreach, it is very powerful and widely used (maybe a little too widely).
https://www.google.com/search?q=php%20foreach
To get the value from repeater use this :
$slides = get_field('slideshow');
if($slides){
foreach($slides as $slide){
echo $slide['videoWebm'];
echo $slide['text'];
echo $slide['kund]'];
echo $slide['link1'];
echo $slide['link2'];
}
}

PHP - Comparing two multidimensional arrays

I have two arrays with data in them and I need to compare the two and create one final array.. here is my situation:
// grab a list of the folders
$folders = glob("../*",GLOB_ONLYDIR);
// create empty array's which will contain our data
$projects_data = array();
$folders_array = array();
// list the contents of the config file
$data = json_decode(file_get_contents('.my-config'), true);
// loop through our data file
foreach($data['web_app']['projects'] as $project) :
// update our projects data array
$projects_data[] = $project;
endforeach;
// loop through each folder on our localhost
foreach($folders as $folder) :
// update our folders array
$folders_array[] = array(
'folder' => basename($folder),
'last_modified' => filemtime($folder),
'dir_size' => dirsize($folder)
);
endforeach;
so I have two arrays.. like so:
$projects_data array
Array
(
[0] => Array
(
[folder] => GitHub Clones
[last_modified] => 1379974689
[dir_size] => 6148
)
[1] => Array
(
[folder] => MagentoPlayground
[last_modified] => 1380336582
[dir_size] => 82340978
)
[2] => Array
(
[folder] => Projects
[last_modified] => 1380581312
[dir_size] => 5954
)
)
$folders_array array
Array
(
[0] => Array
(
[folder] => MagentoPlayground
[last_modified] => 1380336582
[dir_size] => 82340978
)
[1] => Array
(
[folder] => Projects
[last_modified] => 1380581312
[dir_size] => 5933
)
[2] => Array
(
[folder] => old
[last_modified] => 1371064970
[dir_size] => 63385844
)
)
I need to compare these two arrays.. If there is one that exists in the top array and does not exist in the second array (Github Clones) then I need to remove it. If there is one that exist in the bottom array that does not exist in the top array (old) then I need to add it. I guess I will need a third array with the new data but I'm not sure how to structure this.
Also, if there are two entries in both arrays (MagentoPlayground) I need the new array to use the data from the bottom array. The bottom array will have the most up to date last_modified stamp and directory size.
Thanks for any help.
I'd compare using the rules you've just mentioned:
Exists in A but not in B -> remove
Exists in B but not in A -> add
...and create a third and final array. Due to the first rule, you may as well loop through array B as comparison which will solve that one.
<?php
// multidimensional array key search (one deep)
function m_array_key_exists($key, $array) {
foreach($array as $subkey => $subvalue) {
if($subkey === $key)
return true;
if(is_array($subvalue)){
if(array_key_exists($key, subvalue))
return true;
}
}
return false;
}
?>
Seems from those two rules alone that you may as well just take your second array, because if it exists in both arrays it can stay, if it doesn't exist in B you are going to remove it, but it's not there anyway, and if it exists in B but not A you add it, but it's already there...
Use m_array_key_exists as above to check one level deeper than array_key_exists() whether an array key exists in arrays like you've shown. If your rules aren't as simple as I've thought they are, it sounds to me like you want to loop through your second array, check for array keys, apply your special rules and add the result to the third array.

how to get value from array with 2 keys

i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.

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

Array in array in array

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?

Categories