Good day everyone.
I have an regular array (this is the print_r result, the array can have from 1 to n positions):
Array
(
[1] => value1
[2] => value2
[3] => value3
)
I have another array defined elsewhere as:
$array_def['value1']['value2']['value3'] = array(
'fl' => 'field1',
'f2' => 'field2',
);
Using the first array result, how can i check if $array_def exists? In other words, i need to use a flat array values to check if a multidimensional array correspondence exists; keep in mind that the values can repeat in the first array, therefore flipping values with keys it's not an option as it will collide and remove duplicated values.
Thanks in advance.
You can do it this way:
$a = array(1=>'value1', 2=>'value2', 3=>'value3');
$array_def[$a[1]][$a[2]][$a[3]] = array(
'fl' => 'field1',
'f2' => 'field2',
);
I don't think there's any shortcut or special built-in function to do this.
Found the perfect function for you. returns not only exists, but position within a multi-dimensional array..
http://www.php.net/manual/en/function.array-search.php#47116
dated: 03-Nov-2004 11:13
too much to copy/paste
you can then loop over your flat array and foreach:
multi_array_search($search_value, $the_array)
Related
I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.
This question already has answers here:
How to re-index all subarray elements of a multidimensional array?
(6 answers)
Closed 2 years ago.
I use a PHP array to store data about all the people a user is following on a website. Here is an example of how I have it set up:
$data = array(
['user1'] => array(
[0] => 'somedata',
[1] => 'moredata',
[2] => array(
[0] => 'Jim',
[1] => 'Bob',
[2] => 'Nick',
[3] => 'Susy',
)
),
);
As you can see, it is $data[user][2] that lists all the friends. The array has this exact appearance with [0] and [1] for keys because that is how var_export() does it. Now my problem is this. When someone unfollows somebody, I use unset() to delete that friend from the array. So if I want to unfollow Bob in the example above, it would be left with Jim, Nick, and Susy.
The only issue now is that the array keys do not renumber properly when they rename. So once Bob is gone it goes from 0 to 2 rather than Nick taking on the array key of 1. Now I can think of ways to do this myself but I would highly prefer if there were some PHP function specifically for solving this issue, that is, renaming these array keys to the proper numerical order. I checked out the sort() function but that seems for alphabetizing array values not keys.
You can use array_values to re index the array numerically.
$newArray = array_values($array);
If you just want to re-index the array at that level, you could simply use array_values();
For example, assuming you are removing the "bob" entry, just call array_values at the level directly above bob after removing it.
unset($data['user1'][2][1]);
$data['user1'][2] = array_values($data['user1'][2]);
I'd use array_values like this:
$data['user1'][2]=array_values($data['user1'][2]);
Here's the full code:
$data = array(
'user1' => array(
'somedata',
'moredata',
array(
'Jim',
'Bob',
'Nick',
'Susy',
)
),
);
unset($data['user1'][2][1]);
var_export ($data['user1'][2]);
echo "\n\n";
$data['user1'][2]=array_values($data['user1'][2]);
var_export($data['user1'][2]);
Result
array (
0 => 'Jim',
2 => 'Nick',
3 => 'Susy',
)
array (
0 => 'Jim',
1 => 'Nick',
2 => 'Susy',
)
See it in action here:
Sandbox
You could use array_splice
$removedElement = array_splice($data['user1'][2], $indexOfUserToRemove, 1);
This alters the original array reindexing it, but only if the keys of the array are numeric.
Just a quick one i need to get a value from an array the array is made like this
$resultOfAdd[“CaseAndMatterResult”][“ResultInfo”][“ReturnCode”];
and it gives an output of this
Array (
[AddCaseAndMatterResult] => Array (
[ResultInfo] => Array (
[ReturnCode] => OK
[Errors] =>
[Warnings] =>
)
[CaseID] => 4880062
[MatterID] => 4950481
[LeadID] => 0
[CustomerID] => 0
)
)
All i want to do is put the part "MatterID" into a variable. how would I achieve this.
i have tried
$matterID = array($resultOfAdd["MatterID"]);
and this does not work
Regards
This is a multi-dimensional, associative array. Think of it like floors of a building. The key MatterID does not live in the first dimension (floor), rather on the second, in the AddCaseAndMatterResult sub-array.
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID']
Successive dimensions of an array are specified with successive square-brackets, each naming the key to look in (this is true of most languages).
$matterID = $yourArray['AddCaseAndMatterResult']['MatterID'];
Use this way:
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID'];
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?
So I have a multi-dimensional array looks like this.
$config = array(
"First Name" => array(
"user" => $_POST['firstname'],
"limit" => 35,
),
"Last Name" => array(
"user" => $_POST['lastname'],
"limit" => 40,
),
);
I want use the array that's within the config array, so my approach is to use a foreach loop.
foreach($config as $field => $data) {
}
Now I know that $data will be my array, but it seems I can't use it outside of the foreach statement because I only get half of whats already there. Using print_r you can see what it shows outside the loop:
Array
(
[user] => lastname
[limit] => 40
)
But when inside the loop and I use print_r here is my result:
Array
(
[user] => firstname
[limit] => 35
)
Array
(
[user] => lastname
[limit] => 40
)
I imagine it has to do something with it being with the foreach loop. I've tried to run a foreach on the $data array to populate another array, but that didn't work as well.
Is there a way to use this outside of a foreach loop?
Sorry if this a dumb question, I'm sure there is a quite a simple answer to this, but I'm just stumped, and can't think of a way to do this. Thanks.
$config['First Name'] will return the first array, $config['Last Name'] the second.
E.g.
$first_name_config = $config['First Name'];
If you looped over the array, then $data will point to the last element of the array when the looped finished.
Is this what you want? If not, please clarify your question.
In any way, you might want to read about Arrays in PHP.
You can access the two subarrays as $config['First Name'] and $config['Last Name'].
Is that what you want to do?
The trick is to understand that this isn't really a multidimensional array, i.e. it's not stored as a grid or a matrix (unlike true multidimensional arrays in e.g. C). Rather it's just arrays stored within an array.
To answer your headline question, it rather depends on what you mean by "retrieve"!