Looping in a multidimensional Array using PHP - php

I'm having a hard time looping in a multidimensional array. I'm not an expert of some sort when it comes to PHP. What I want to happen is to search for a certain field. If it hits the right field, then it will grab the data and store in a variable and if it does not hit the right field, it will continue to search for the right field.
Here's the array
[111] => Array
(
[tag] => B:VALUE
[type] => close
[level] => 7
)
[112] => Array
(
[tag] => B:KEYVALUEOFINTHEALTHAGENCYD9J3W_PIR
[type] => close
[level] => 6
)
[113] => Array
(
[tag] => A:AGENCIES
[type] => close
[level] => 5
)
[114] => Array
(
[tag] => A:TOKEN
[type] => complete
[level] => 5
[value] => vy8BMS8nDIFdQWRTb6wyNDGGUMgBzHtOXU6mHqZgdxhRAbi0qkwluK9pjt03OQyf
)
[115] => Array
(
[tag] => LOGINCAREGIVERPORTALRESULT
[type] => close
[level] => 4
)
[116] => Array
(
[tag] => LOGINCAREGIVERPORTALRESPONSE
[type] => close
[level] => 3
)
[117] => Array
(
[tag] => S:BODY
[type] => close
[level] => 2
)
[118] => Array
(
[tag] => S:ENVELOPE
[type] => close
[level] => 1
)
and here's my code and I would like to apologize first for not being able to complete it. :D ......i have totally no idea on what to place.....and searching is making me more confuse...sorry....
here's the code
$last = count($vals) - 1;
foreach ($vals as $i => $row) {
if (!$vals == '114') {
next
}
else {
$sessiontoken = <------store the value here
}
}

Try the following:
foreach ($values as $key => $value){
if ($key == '114') {
if($value['tag']==='A:TOKEN')
$sessiontoken = $value['value'];
}
}

Your actual question suggests you are looking to always return key '114'. In that case, you don't need a loop at all, just reference that key:
$sessiontoken = $vals['114']['value'];
However, what I think you actually want is to find whichever element has a 'tag' of 'A:TOKEN', which would look like this:
foreach ($vals as $i => $row) {
// Here, $row is one item from the $vals array
// You don't want to think about $vals in the condition, just $row
if ( $row['tag'] != 'A:TOKEN' ) {
continue; // there's no "next" keyword in PHP
}
else {
$sessiontoken = $row['value'];
}
}
I'd probably swap the if around like this, though:
foreach ($vals as $i => $row) {
if ( $row['tag'] == 'A:TOKEN' ) { // Positive tests are easier to read
$sessiontoken = $row['value'];
}
// you can look for other tags at the same time with elseif ( ... )
else {
continue; // only if none of your conditions are met
}
// if there's nothing after the end of the else,
// you don't need the continue at all
}

Assuming you want to find the the session token which is contained in only one of your results. Do the following:
foreach ($vals as $i => $array_value){
if (isset($array_value[$i]['value']) {
$sessiontoken = $array_value[$i]['value'];
break; // stop looping after it is found
}
}

This one liner right here should be fixed:
if (!$vals == '114') {
Assuming that you want to store the session if you found the item you want at position 114, you should do something like this. I'm under the assumption that you have an array at position 114, and then you have keys that are pointing to a value? It seems like from your description that each key is actually an array that points to a value? Assuming that it's a regular key-value pair, here's something you can try:
foreach ($vals as $key=>$value)
{
if ($key !== '114')
{
continue;
} else {
// check if value exists
if (!empty($value['value'])
{
$sessionToken = $value['value'];
}
}
}
If it's not a key-value pair, then you need to adjust it to something like:
foreach ($vals as $key=>$value)
{
if ($key !== '114')
{
continue;
} else {
foreach ($value as $keyArray => $val)
{
if ($keyArray == 'value')
{
$sessionToken = $value['value'];
}
}
}
}

Related

Removing elements from multidimensional array

Hi I am having a few issues unsetting an entire row from a multidimensional array. I have an array that takes the following format
Array
(
[0] => Array
(
[ID] => 10000
[Date] => 21/11/2013
[Total] => 10
)
[1] => Array
(
[ID] => 10001
[Date] => 21/12/2013
[Total] => abc
)
...
)
I am looping this array to check that the Total contains only numbers or a period.
foreach($this->csvData as &$item) {
foreach($item as $key => $value) {
if($key === 'Total') {
$res = preg_replace("/[^0-9.]/", "", $item[$key] );
if(strlen($res) == 0) {
unset($item[$key]);
} else {
$item[$key] = $res;
}
}
}
}
So you can see from my array, the second element Total contains abc, therefore the whole element it is in should be removed. At the moment, with what I have, I am getting only that element removed
[1] => Array
(
[ID] => 10001
[Date] => 21/12/2013
)
How can I remove the whole element?
Thanks
Try this:
//Add key for outer array (no longer need to pass-by-reference)
foreach($this->csvData as $dataKey => $item) {
foreach($item as $key => $value) {
if($key === 'Total') {
$res = preg_replace("/[^0-9.]/", "", $item[$key] );
if(strlen($res) == 0) {
// Unset the key for this item in the outer array
unset($this->csvData[$dataKey]);
} else {
$item[$key] = $res;
}
}
}
}

How can I filter a multidimentional array for duplicates?

I have an array set up like:
Array (
[0] => Array ( [stage] => biometrics [applicant_id] => b79a4c6ea30611e3a3160675fe500303 )
[1] => Array ( [stage] => biometrics [applicant_id] => b79a4c6ea30611e3a3160675fe600303 )
[2] => Array ( [stage] => biometrics [applicant_id] => b79a4c6ea30611e3a3160675fe700303 )
[3] => Array ( [stage] => biometrics [applicant_id] => b79a4c6ea30611e3a3160675fe800303 )
[4] => Array ( [stage] => biometrics_queue [applicant_id] => b79a4c6ea30611e3a3160675fe900303 )
)
First, I want to check to see if there are any duplicate applicant_id's then I need to check the stages for the duplicates. If the applicant_id are the same, but stages are different, they are ok, If the applicant_id's are the same and stages are either the same (biometrics & biometrics) or if it is (biometrics and biometrics_queue) I need to delete that entry from the array.
Not sure how to do this.
.
So here is what I have so far. It works, but there are a lot of loops going on, don't wanna end up using too many resources or getting into an infinite loop...Does anyone see anything wrong with what I'm doing?
First, I used a function called convert stages, so that if there is anything that is a stage name and then _queue appended to the end, it changes it to just the stage name.
foreach ($timer_entry as $key => $value){
$timer_entry[$key]['stage'] = convert_stages($timer_entry[$key]['stage']);
}
Then I have a foreach inside of a for, checking for applicant_id's that might be the same:
for ($i = 0; $i < count($timer_entry); $i++) {
foreach ($timer_entry as $key => $value){
if ($key == $i) {
continue;
}
else {
if ($timer_entry[$key]['applicant_id'] == $timer_entry[$i]['applicant_id']) {
if ($timer_entry[$key]['stage'] == $timer_entry[$i]['stage']) {
unset($timer_entry[$key]);
}
}
}
}
}
If they are the same, I unset them.
I didn't test it, but I think this might do the trick:
$array = array_map('unserialize', array_unique(array_map('serialize', $array)));
How about:
foreach( $myArray as $index => $element )
if (isset($tmp[$element['applicant_id']][str_replace('_queue','',$element['stage'])])
unset($myArray[$index]);
else
$tmp[$element['applicant_id']][str_replace('_queue','',$element['stage'])] = true;

After deleting the particular multidimensional array element in PHP, the Next array elements are not positioning automatically

I've created the multidimensional array in the following format
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [1] => Array ( [id] => 9 [quantity] => 2 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
When I try to unset an particular array element based on id, after unset i'm getting the array like below.
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
The array element is getting unset, but the next array element doesn't move to the deleted array position.
For unset an array element, I'm using the following code.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
How to solve this issue? Please kindly help me to solve it.
Thanks in advance.
Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
array_values($cartdetails['products']);
Using unset doesn't alter the indexing of the Array. You probably want to use array_splice.
http://www.php.net/manual/en/function.array-splice.php
http://php.net/manual/en/function.unset.php
Why do you use $i++ to find an element to unset?
You can unset your element inside foreach loop:
foreach($cartdetails['products'] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}
// in your case array_values will "reindex" your array
array_values($cartdetails['products']);
Why don't you use this???
$id = 9;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}

Replacing values in the array nvp

I have been trying to replace the values in the array
I'll name this array as $currencies when i print this it looks like.
Array
(
[0] => Array
(
[currencylabel] => USA, Dollars
[currencycode] => USD
[currencysymbol] => $
[curid] => 1
[curname] => curname1
[check_value] =>
[curvalue] => 0
[conversionrate] => 1
[is_basecurrency] => 1
)
[1] => Array
(
[currencylabel] => India, Rupees
[currencycode] => INR
[currencysymbol] => ₨
[curid] => 2
[curname] => curname2
[check_value] =>
[curvalue] => 0
[conversionrate] => 50
[is_basecurrency] =>
)
[2] => Array
(
[currencylabel] => Zimbabwe Dollars
[currencycode] => ZWD
[currencysymbol] => Z$
[curid] => 3
[curname] => curname3
[check_value] =>
[curvalue] => 0
[conversionrate] => 22
[is_basecurrency] =>
)
)
Here I am having a $conversionRate to which i need to divide the values present in the array $currencies [0] -> Array -> [conversionrate] and replace in the same place in array.
and the same operation for [1] -> Array -> [conversionrate] and so on..
for which my current approach is as follows
$conversionRate = 50;
foreach ($currencies as $key => $val) {
$key['conversionrate'] = $key['conversionrate'] / $conversionRate;
if($key['conversionrate'] == 1) {
$key['is_basecurrency'] = 1;
} else {
$key['is_basecurrency'] = '';
}
}
print_r($key);
die;
Currently this is not working kindly help
Your loop is all wrong, there is no $key['conversionrate'], it's $val['conversionrate']. In fact there doesn't seems to be a reason for the $key variable, you can just loop through the array with
foreach ($currencies as &$val)
Also, you probably want to print_r($currencies), not $key
Do not compare floating point numbers with == to 1, it might not work due to rounding errors.
You mixed up key and value and you need to use &$val to be able to change the array.
$conversionRate = 4;
foreach ($currencies as $key => &$val) {
if($val['conversionrate'] == $conversionRate) {
$val['is_basecurrency'] = 1;
} else {
$val['is_basecurrency'] = '';
}
$val['conversionrate'] = $val['conversionrate'] / $conversionRate;
}
unset($val);
print_r($currencies);
die;
$key is an index identofoer of an array and $val contain array values
so use like this
$conversionRate = 4;
foreach ($currencies as $key => $val) {
$val['conversionrate'] = $val['conversionrate'] / $conversionRate;
if($val['conversionrate'] == 1) {
$val['is_basecurrency'] = 1;
} else {
$val['is_basecurrency'] = '';
}
}
print_r($val);
die;

Find value and key in multidimensional array

I have the following array:
Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
I need to find if [position] => 22 exists in my array and retain the array path for further reference. Thank you.
Example of code for the solution "Ancide" provide.
$found = false;
foreach ($array as $array_item) {
if (isset($array_item['position'] && $array_item['position'] == "22")) {
$found = true;
break;
}
}
You can try this code:
$array = array
(
array (
"word" => 1,
"question" => php,
"position" => 11
),
array (
"word" => sql,
"question" => 1,
"position" => 22
)
);
foreach($array as $item)
{
foreach($item as $key=>$value)
{
if($key=="position" && $value=="22")
{
echo "found";
}
}
}
First check if they key exists using isset, then if the key exists, check that the value is equal to your compare value.
Edit: I missed that there were two arrays. To solve this, iterate through each array and do the check in each cycle. If the check is positive you know which array it is by looking at the current index.
I think there is no other solution than to loop through the array an check whether there is a key "position" and value "22"
This will solve your problem:
<?php
foreach ($array as $k => $v) {
if(isset($v['position']) && $v['position'] == 22) {
$key = $k;
}
}
echo $key;
//$array[$key]['position'] = 22
?>
Try this:
function exists($array,$fkey,$fval)
{
foreach($array as $items)
{
foreach($items as $key => $val)
if($key == $fkey and $val == $fval)return true;
}
return false;
}
Example:
if(exists($your_array,"position",22))echo("found");
function findPath($array, $value) {
foreach($array as $key => $subArray) if(subArray['position'] === $value) return $key;
return false; // or whatever if not found
}
echo findPath($x, 22); // returns 1
$x= Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
Try with this function:
function findKey($array, $mykey) {
if(array_key_exists($mykey, $array))
return true;
foreach($array as $key => $value) {
if(is_array($value))
return findKey($value, $mykey);
}
return false;
}
if(findKey($search_array, 'theKey')) {
echo "The element is in the array";
} else {
echo "Not in array";
}

Categories