I have a huge array in which keys are also not constant in most of the cases, but there are 3 keys that always constant (#name,#default_value,#value) and #default_value and #value is different i want to get these kind of sub arrays in 1 simple array , for this purpose i am using recursion in whole array and checking out if these 3 keys are present there i can print these values inside recursion easily but I am not able to get those values in return. So that i can precess them further.
$form=array();
$form['field_one']['#name']="field_one";
$form['field_one']['#default_value']="old";
$form['field_one']['#value']="new";
$form['field_two']['#name']="field_two";
$form['field_two']['#default_value']="old";
$form['field_two']['#value']="new";
$form['field_three']['#name']="field_three";
$form['field_three']['#default_value']="old";
$form['field_three']['#value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#name']="field_four";
$form['thiscouldbeanotherarray']['idk']['field_four']['#default_value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#value']="new";
$arr_get = get_updatedvalues($form,array());
var_dump($arr_get);
function get_updatedvalues($form,$fields) {
if (!is_array($form)) {
return;
}
foreach($form as $k => $value) {
if(str_replace('#','',$k) =='default_value' && ($form['#default_value'] != $form['#value'] ) ){
$fields['field'][$form['#name']] = array("name" => $form['#name'],"old_value" =>$form['#default_value'],"new_value" =>$form['#value']);
var_dump($fields);
}
get_updatedvalues($value,$fields);
}
return $fields;
}
If you run this code it will give you $arr_get > array (size=0), there i need all three values
If I understand correctly, you need to pass fields as a reference in order to change it:
function get_updatedvalues($form, &$fields) {
To do that, however, you'll need to change your initial call so that you have a variable to pass as the reference:
$array = [];
$arr_get = get_updatedvalues($form,$array);
Running this I get:
Array
(
[field] => Array
(
[field_one] => Array
(
[name] => field_one
[old_value] => old
[new_value] => new
)
[field_two] => Array
(
[name] => field_two
[old_value] => old
[new_value] => new
)
[field_four] => Array
(
[name] => field_four
[old_value] => old
[new_value] => new
)
)
)
Related
Array
(
[0] => Array
(
[datas] => Array
(
[res] => 1
[rows] => Array
(
[0] => stdClass Object
(
[a] => 11
[b] => 901
[c] => 2
[d] => 2
[e] => A
[f] => BT
[g] => arushi
[h] => arushi#gmail.com
[i] => 123445
[j] => 12355.jpg
)
)
)
)
[1] => Array
(
[datas] => Array
(
[res] => 1
[rows] => stdClass Object
(
[person_name] => arushi
)
)
)
)
if i get the value in that kind off array how can i get the value of
both partially with different variable m not able to understand the
structure of the array..
need to get the value in table seperatly in different different table with same page how i can get the values
You would need to do a foreach loop. The only problem is that if you want to make it dynamic and grab the data by itself without you telling it what to get. If not it means you would have to know exactly what you need and the structure of your results. But seeing that there is a pattern you can do some checks until you reach rows. For example ($array would be the variable that has the data you provided):
foreach ($array AS $arr) {
// To make you function/check work faster,
// before even entering to fetch for data
// you can check if it has any data, else you
// probably will end up with an error
if (isset ($arr ['datas']) && $arr ['datas']) {
foreach ($arr ['datas'] AS $data) {
if (isset ($arr ['res']) && 0 < $arr ['res']) {
// here is where it gets tricky because
// from you example its either an array or an object
// but the kool part about it is that you can convert an object into an array
// or just leave it as is because the foreach will take care of it either way :)
// first check it it is an object and convert if yes
$row = $arr ['rows'];
if (!is_array ($row))
$row = (array)$row; // converting it to array is super easy :)
foreach ($row AS $key=>$dat) {
// from here your result can either be another array or just data
// so you run the check once more
if (is_array ($dat)) {
foreach ($dat AS $k=>$d) {
echo "data for $k is $d";
}
}
else
echo "data for $key is $dat";
}
}
}
}
}
You can use foreach to loop through the arrays which have keys starting from 0 to n. So that you can foreach through the main array to get the datas array for all the keys. For getting rows childs you can use another foreach inside it to get each items. But for rows it is object , so you have to use -> to select the key. see below example code. But on your array the second array consist different formate in rows array. so make it like a common formate to loop through it easily.
For eg :-
foeach($parent_array as $array){
$data=$array['datas'];
$res = $data['res'];
$rows=$data['rows'];
foreach($rows as $row){
echo $row->a; // to get the value of key a = 11
}
}
I have the following loop that creates an array
while($row1 = mysqli_fetch_assoc($result1))
{
$aliens[] = array(
'username'=> $row1['username'],
'personal_id'=> $row1['personal_id']
);
}
It produces the following result
Array (
[0] =>
Array ( [username] => nimmy [personal_id] => 21564865 )
[1] =>
Array ( [username] => aiswarya [personal_id] => 21564866 )
[2] =>
Array ( [username] => anna [personal_id] => 21564867 )
Then I have another loop as follows, inside which, I need to fetch the personal_id from the above array. I fetch it as follows.
foreach($aliens as $x=>$x_value)
{
echo $aliens['personal_id'];
//some big operations using the
$aliens['personal_id']; variable
}
However, I can't get the values if personal_ids. I get it as null. What seems to be the problem? How can I solve it?
You have an array of "aliens", each alien is an array with personal_id and username keys.
foreach ($aliens as $index => $alien) {
echo $alien['personal_id'], PHP_EOL;
}
The foreach loop iterates its items (aliens). The $alien variable represents the current iteration's item, i.e. the alien array.
foreach($aliens as $x=>$x_value)
{
echo $x_value['personal_id'];
//some big operations using the
$x_value['personal_id']; variable
}
I am having trouble sorting through a multidimensional array that I am pulling from an XML feed that can be different every time. I need to find something and place the result in a variable. I am still learning PHP and this unfortunately is a bit over my head.
I'll break down what I have. An example of my array contained in $valsarray:
Array
( [0] => Array
(
[tag] => GIVENNAME
[type] => complete
[level] => 8
[value] => peter
)
[1] => Array
(
[tag] => FAMILYNAME
[type] => complete
[level] => 8
[value] => rabbit
)
[2] => Array
(
[tag] => COMPLETENUMBER
[type] => complete
[level] => 9
[value] => 123-345-4567
)
[3] => Array
(
[tag] => URIID
[type] => complete
[level] => 9
[value] => customerEmail#gmail.com
)
)
Now I understand that I can get the result by using: $phone = $valsarray[2][value];
However, my problem is that if no phone number was given, the XML feed will not contain the phone number array so Array 3 would become Array 2.
So my question is how would I go about looping through the arrays to find if COMPLETENUMBER exists and then assigning the phone number contained in value to a $phone variable?
Here's one way:
$tags = array_column($valsarray, null, 'tag');
if(isset($tags['COMPLETENUMBER'])) {
$phone = $tags['COMPLETENUMBER']['value'];
}
Or if you only care about value:
$tags = array_column($valsarray, 'value', 'tag');
if(isset($tags['COMPLETENUMBER'])) {
$phone = $tags['COMPLETENUMBER'];
}
So in short:
Get an array of the value values indexed by tag
If COMPLETENUMBER index is set then get the value from value
After the array_column() you can then get whatever value you want:
$email = $tags['URIID'];
This loop would do it:
foreach($valsarray as $fieldArray)
{
if ($fieldArray['tag'] === 'COMPLETENUMBER')
{
$phone = $fieldArray['value'];
break;
}
}
If you need to do this type of thing repeatedly on the same array, you'd be better off reindexing it than searching each time. You could reindex like this:
foreach($valsarray as $key => $fieldArray)
{
$valsarray[$fieldArray['tag']] = $fieldArray;
unset($valsarray[$key]);
}
After reindexing it, you can do this for any field you want:
$phone = $valsarray['COMPLETENUMBER']['value'];
You can array_filter to get only COMPLETENUMBER entries, and set $phone if one is found.
$items = array_filter($valsarray, function($x) { return $x['tag'] == 'COMPLETENUMBER'; });
$phone = $items ? reset($items)['value'] : null;
Based on your other comments, if you want to get the values for a subset of tags from the array, you can use in_array in the array_filter callback. This could be wrapped in the array_column suggested in AbraCadaver's answer to get an array of values for any of the tags you're interested in:
$tags = ['COMPLETENUMBER', 'URIID'];
$data = array_column(array_filter($valsarray, function($x) use ($tags) {
return in_array($x['tag'], $tags);
}), 'value', 'tag');
The result would be like:
array (size=2)
'COMPLETENUMBER' => string '123-345-4567' (length=12)
'URIID' => string 'customerEmail#gmail.com' (length=23)
Most likely I'm doing this wayyyyyy too complicated. But I'm in the need of converting multiple arrays to multidimensional array key's. So arrays like this:
Array //$original
(
[0] => 500034
[1] => 500035 //these values need to become
//consecutive keys, in order of array
)
Needs to become:
Array
(
[50034][50035] => array()
)
This needs to be done recursively, as it might also require that it becomes deeper:
Array
(
[50034][50036][50126] => array() //notice that the numbers
//aren't necessarily consecutive, though they are
//in the order of the original array
)
My current code:
$new_array = array();
foreach($original as $k => $v){ //$original from first code
if((gettype($v) === 'string' || gettype($v) === 'integer')
&& !array_key_exists($v, $original)){ //check so as to not have illigal offset types
$new_array =& $original[array_search($v, $original)];
echo 'In loop: <br />';
var_dump($new_array);
echo '<br />';
}
}
echo "After loop <br />";
var_dump($new_array);
echo "</pre><br />";
Gives me:
In loop:
int(500032)
In loop:
int(500033)
After loop
int(500033)
Using this code $new_array =& $original[array_search($v, $original)]; I expected After loop: $new_array[50034][50035] => array().
What am I doing wrong? Been at this for hours on end now :(
EDIT to answer "why" I'm trying to do this
I'm reconstructing facebook data out of a database. Below is my own personal data that isn't reconstructing properly, which is why I need the above question answered.
[500226] => Array
(
[own_id] =>
[entity] => Work
[name] => Office Products Depot
[500227] => Array
(
[own_id] => 500226
[entity] => Employer
[id] => 635872699779885
)
[id] => 646422765379085
)
[500227] => Array
(
[500228] => Array
(
[own_id] => 500227
[entity] => Position
[id] => 140103209354647
)
[name] => Junior Programmer
)
As you can see, the ID [500227] is a child of [500226], however, because I haven't got the path to the child array, a new array is created. The current parentage only works to the first level.
[own_id] is a key where the value indicates which other key should be its parent. Which is why the first array ([500226]) doesn't have a value for [own_id].
If you want to do something recursively, do it recursively. I hope that's what you meant to do.
public function pivotArray($array, $newArray)
{
$shifted = array_shift($array);
if( $shifted !== null )
{
return $this->pivotArray($array, array($shifted=>$newArray));
}
return $newArray;
}
$array = array(432, 432532, 564364);
$newArray = $this->pivotArray($array, array());
Edit: After the question's edit it doesn't seem to be very relevant. Well, maybe someone will find it useful anyway.
I know there are a lot of answers on multi-dimensional arrays but I couldn't find what I was looking for exactly. I'm new to PHP and can't quite get my head around some of the other examples to modify them. If someone could show me the way, it would be much appreciated.
An external service is passing me the following multidimensional array.
$mArray = Array (
[success] => 1
[errors] => 0
[data] => Array (
[0] => Array (
[email] => me#example.com
[id] => 123456
[email_type] => html
[ip_opt] => 10.10.1.1
[ip_signup] =>
[member_rating] => X
[info_changed] => 2011-08-17 08:56:51
[web_id] => 123456789
[language] =>
[merges] => Array (
[EMAIL] => me#example.com
[NAME] => Firstname
[LNAME] => Lastname
[ACCOUNT] => ACME Ltd
[ACCMANID] => 123456adc
[ACCMANTEL] => 1234 123456
[ACCMANMAIL] => an.other#example.com
[ACCMANFN] => Humpty
[ACCMANLN] => Dumpty
)
[status] => unknown
[timestamp] => 2011-08-17 08:56:51
[lists] => Array ( )
[geo] => Array ( )
[clients] => Array ( )
[static_segments] => Array ( )
)
)
)
The only information I'm interested in are the key/value pairs that are held in the array under the key name 'merges'. It's about the third array deep. The key name of the array will always be called merges but there's no guarantee that its location in the array won't be moved. The number of key/value pairs in the merges array is also changeable.
I think what I need is a function for array_walk_recursive($mArray, "myfunction", $search);, where $search holds the string for the Key name (merges) I'm looking for. It needs to walk the array until it finds the key, check that it holds an array and then (preserving the keys), return each key/value pair into a single array.
So, for clarity, the output of the function would return:
$sArray = Array (
[EMAIL] => me#example.com
[NAME] => Firstname
[LNAME] => Lastname
[ACCOUNT] => ACME Ltd
[ACCMANID] => 123456adc
[ACCMANTEL] => 1234 123456
[ACCMANMAIL] => an.other#example.com
[ACCMANFN] => Humpty
[ACCMANLN] => Dumpty
)
I can then move on to the next step in my project, which is to compare the keys in the single merges array to element IDs obtained from an HTML DOM Parser and replace the attribute values with those contained in the single array.
I probably need a foreach loop. I know I can use is_array to verify if $search is an array. It's joining it all together that I'm struggling with.
Thanks for your help.
Would this work?
function find_merges($arr)
{
foreach($arr as $key => $value){
if($key == "merges") return $value;
if(is_array($value)){
$ret = find_merges($value);
if($ret) return $ret;
}
}
return false;
}
It would do a depth-first search until you either ran out of keys or found one with the value merges. It won't check to see if merges is an array though. Try that and let me know if that works.
Here is a general purpose function that will work it's way through a nested array and return the value associated with the first occurance of the supplied key. It allows for integer or string keys. If no matching key is found it returns false.
// return the value a key in the supplied array
function get_keyval($arr,$mykey)
{
foreach($arr as $key => $value){
if((gettype($key) == gettype($mykey)) && ($key == $mykey)) {
return $value;
}
if(is_array($value)){
return get_keyval($value,$mykey);
}
}
return false;
}
// test it out
$myArray = get_keyval($suppliedArray, "merges");
foreach($myArray as $key => $value){
echo "$key = $value\n";
}
A recursive function can do this. Returns the array or FALSE on failure.
function search_sub_array ($array, $search = 'merges') {
if (!is_array($array)) return FALSE; // We're not interested in non-arrays
foreach ($array as $key => $val) { // loop through array elements
if (is_array($val)) { // We're still not interested in non-arrays
if ($key == $search) {
return $val; // We found it, return it
} else if (($result = search_sub_array($array)) !== FALSE) { // We found a sub-array, search that as well
return $result; // We found it, return it
}
}
}
return FALSE; // We didn't find it
}
// Example usage
if (($result = search_sub_array($myArray,'merges')) !== FALSE) {
echo "I found it! ".print_r($result,TRUE);
} else {
echo "I didn't find it :-(";
}
So you want to access an array within an array within an array?
$mergeArray = NULL;
foreach($mArray['data'] as $mmArray)
$mergeArray[] = $mmArray['merges'];
Something like that? If merges is always three deep down, I don't see why you need recursion. Otherwise see the other answers.
Here's another approach, mostly because I haven't used up my iterator quota yet today.
$search = new RegexIterator(
new RecursiveIteratorIterator(
new ParentIterator(new RecursiveArrayIterator($array)),
RecursiveIteratorIterator::SELF_FIRST),
'/^merges$/D', RegexIterator::MATCH, RegexIterator::USE_KEY
);
$search->rewind();
$merges = $search->current();
array_walk_recursive() is brilliant for this task! It doesn't care what level the key-value pairs are on and it only iterates the "leaf nodes" so there is not need to check if an element contains a string. Inside of the function, I am merely making a comparison on keys versus the array of needles to generate a one-dimensional result array ($sArray).
To be clear, I am making an assumption that you have predictable keys in your merges subarray.
Code: (Demo)
$needles=['EMAIL','NAME','LNAME','ACCOUNT','ACCMANID','ACCMANTEL','ACCMANMAIL','ACCMANFN','ACCMANLN'];
array_walk_recursive($mArray,function($v,$k)use(&$sArray,$needles){if(in_array($k,$needles))$sArray[$k]=$v;});
var_export($sArray);
Output:
array (
'EMAIL' => 'me#example.com',
'NAME' => 'Firstname',
'LNAME' => 'Lastname',
'ACCOUNT' => 'ACME Ltd',
'ACCMANID' => '123456adc',
'ACCMANTEL' => '1234 123456',
'ACCMANMAIL' => 'an.other#example.com',
'ACCMANFN' => 'Humpty',
'ACCMANLN' => 'Dumpty',
)