How to check if value is equal to string in array - php

I want to check if the value: diam-mm exist in array, if the value not exist do something.
A array can have multiple properties, property name is: [PropertyType]->[Name]
i thought i loop to the properties and check if diam-mm value exist, else do something but because of the loop he does import the value mutliple times instead of one time.
Example of one array with properties:
[2] => Array
(
[PropertyType] => Array
(
[Guid] =>
[DataType] => Text
[Name] => diam-mm
[Unit] =>
)
[BooleanValue] =>
[DateTimeValue] =>
[NumericValue] =>
[TextValue] => 400
[XmlValue] =>
[UrlValue] => 400
)
[3] => Array
(
[PropertyType] => Array
(
[Guid] =>
[DataType] => Text
[Name] => lengte-mm
[Unit] =>
)
[BooleanValue] =>
[DateTimeValue] =>
[NumericValue] =>
[TextValue] => 2000
[XmlValue] =>
[UrlValue] => 2000
)

<?php
for ($i=0; $i <count($array) ; $i++) {
if($array[$i]['PropertyType']['Name']=="diam-mm"){
// your code
}
}
?>

If you want to check if an array key matches a value you can do so using simple variable assignment. However you would need to loop through each array index item and enumarate the loop based on it's iteration.
To create the loop I would suggest using count to count the amount of items in the array. We will assign the result to a variable :
$count = count($my_array);
Do keep in mind that count only counts the number of items based on their actual count, not their array index. This means that an array with indexes starting from zero which has an index of 0-30 would return 31 as the result of count because count counted the zero index as an actual count value.
To fix this we need to subtract 1 from the result of count :
$count = $count - 1;
Then we can use the count as the number of repeats in a for loop. Where the variable $i represents the iteration that the loop is going through :
//Loop through each array index
for($i=0; $i <= $count; $i++){
//Assign the value of the array key to a variable
$value = $my_array[$i]['PropertyType']['Name'];
//Check if result string contains diam-mm
if(str_contains($value, 'diam-mm'){
echo 'The value matches!';
} else{
echo 'The value does not match!';
}
}

Try this function, i hope this answer your question...
function array_recursive_search_key_map($needle, $haystack) {
foreach($haystack as $first_level_key=>$value) {
if ($needle === $value) {
return array($first_level_key);
} elseif (is_array($value)) {
$callback = $this->array_recursive_search_key_map($needle, $value);
if ($callback) {
return array_merge(array($first_level_key), $callback);
}
}
}
return false;
}
How to use
$yourValue = "diam-mm";
$array_keymap = array_recursive_search_key_map($yourValue, $yourArray);
var_dump($array_keymap);
Output
Array
(
[0] => 0
[1] => PropertyType
[2] => Name
)

Related

Compare multidimensional array with another array in PHP and get the values from the multidimensional array

I have an multidimensional array from an XML file which I want to compare with a normal array. I need to compare the [tag] name in the multidimensional array with the name in the other array and get value from the multidimensional array that belongs to the tag.
Array
(
[0] => Array
(
[tag] => DOCUMENT
[type] => open
[level] => 1
)
[1] => Array
(
[tag] => SENDERID
[type] => complete
[level] => 2
[value] => TEST
)
[2] => Array
(
[tag] => SENDERSHORTNAME
[type] => complete
[level] => 2
)
[3] => Array
(
[tag] => RECIPIENTID
[type] => complete
[level] => 2
[value] => VGLEE
)
)
Second array which I need to compare it with the multidimensional array:
$compare_array = array('DOCUMENT', 'SENDERID', 'SENDERSHORTNAME', 'RECIPIENTID');
Now I want to check if the key from $compare_array is matched in the multidimensional array. If so, I want to grab the value from the multidimensional array and make a variable with the name from the compare_array and append the value to the variable.
I made a for loop:
for($i = 0; $i < $count; $i++){
if($values[$i]['tag'] == 'SENDERID'){
$SENDER = $values[$i]['value'];
}
if($values[$i]['tag'] == 'RECIPIENTID'){
$RECIPIENTID = $values[$i]['value'];
}
if($values[$i]['tag'] == 'IREF'){
$IREF = $values[$i]['value'];
}
if($values[$i]['tag'] == 'DOCUMENTNUMBER'){
$DOCUMENTNUMBER = $values[$i]['value'];
}
}
For your example data, you could use array_reduce and use in_array to check if the tag is present in $compare_array
If you must make a variable with the name from the $compare_array and append the value to the variable you might use extract with a flag that suits your expectations.
The value is not present in all the example data so you might also check if that exists.
$compare_array = array('DOCUMENT', 'SENDERID', 'SENDERSHORTNAME', 'RECIPIENTID');
$result = array_reduce($arrays, function($carry, $item) use ($compare_array) {
if(isset($item["value"]) && in_array($item["tag"], $compare_array, true)) {
$carry[$item["tag"]] = $item["value"];
}
return $carry;
});
extract($result, EXTR_OVERWRITE);
echo $SENDERID;
echo $RECIPIENTID;
Demo
You can try using array_in() in this case, below is the sample code
for($i = 0; $i < $count; $i++){
if(in_array($values[$i]['tag'],$compare_array)){
$value = $values[$i]['value'];
}
}
For reference in_array()
Try following code:
$array = []; //Complete array to be parsed.
$compare_array = array('DOCUMENT', 'SENDERID', 'SENDERSHORTNAME', 'RECIPIENTID');
foreach ($array as $value) {
if (in_array($value["tag"], $compare_array)) {
$$value["tag"] = $value["value"];
}
}
It will traverse through array and if tag name matched to value $compare_array, then define a variable with tag name and initialize with value.

How can i compare values within a multidimensional array

I am developing a Bio-metric election system but i am facing problem regarding election results.
I got this array after executing a query.
Array
(
[paty1] => Array
(
[NA122] => stdClass Object
(
[count] => 2
)
[NA2] => stdClass Object
(
[count] => 0
)
[NA56] => stdClass Object
(
[count] => 1
)
)
[party2] => Array
(
[NA122] => stdClass Object
(
[count] => 0
)
[NA2] => stdClass Object
(
[count] => 0
)
[NA56] => stdClass Object
(
[count] => 0
)
)
)
This array is stored in $data and it can have unlimited indexes.
Now if count of [Paty1][NA122] is greater then count of [Party2][NA122] so i will declare Party1 win in NA122 and i have to compare it with n number of indexes.
e.g. there is another index pary3 so firstly I will compare count of [party1][NA122] with [party2][NA122] and then with [party3][NA122] and winner will be the one with greater count . Can you please help me??
Thanks in advance
Try this:
foreach(current($Result) as $Const=>$val){
echo "Winner of Constituency '$Const': ". findWinner($Const,$Result).PHP_EOL;
}
function findWinner($Const, $Result){
$Max = 0;
$Winner = '';
foreach($Result as $Party => $ConstList){
if($ConstList[$Const]->count>$Max){
$Max = $ConstList[$Const]->count;
$Winner = $Party;
}
}
return $Winner;
}
Check live code here:
https://www.tehplayground.com/x5sPu7JxuexOdwU8
So you want to get the party with the max count for a given NA#.
You can use a function like this:
function maxParty($data, $na) {
$max = null;
foreach($data as $party => $values) {
if(is_null($max)) {
$max = $party;
continue;
} else {
if($values[$na]->count > $data[$max][$na]->count) {
$max = $party;
}
}
}
return $max;
}
Then you feed this function with a $data array and the NA# you want to calculate the max party with. For example
$winner = maxParty($data, 'NA122');
It will return the key for the winner party. I.e. "party1"
Do you mean something like this:
<?php
$data=getData();
$maxValue;
$maxKey;
foreach($data as $key => $paty)
if(!isset($maxValue) || $paty->count>$maxValue){
$maxValue=$paty->count;
$maxKey=$key;
}
echo "$maxValue $maxKey";
function getData(){
$a=array();
for($i=1;$i<100;$i++)
$a["paty$i"]=(object) array("count"=>$i);
return $a;
}
?>
Explanation:
getData returns an array like the one you described
foreach($data as $key => $paty) - iterates through the entire array
if ( ) -- checks if the current value is greater than the previous max
If you want to know more about PHP:
foreach, objects, arrays and google

How to fetch one array value from the array?

Hi I have array like this
Array (
[0] => stdClass Object (
[id] => 1930 [value] => 20)
[1] => stdClass Object (
[id] => 1931 [value] => 30 )
[2] => stdClass Object (
[id] => 1937 [value] => 30 )
[3] => stdClass Object (
[id] => 1938 [value] => 20 )
)
I want to fetch random array from this. The Id which has greater value(%) should be fetched more time (That value is %).
Make a another array and repeat the index of array for the number of times its value is and then fetch the values randomly this would do what you want
The above mentioned array would be
array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,)
$arr = Array (
(Object) array (id => 1930, value => 20),
(Object) array (id => 1931, value => 30),
(Object) array (id => 1937, value => 30),
(Object) array (id => 1938, value => 20));
// count sum of all values
$sum = array_reduce($arr, function ($c, $i) { return $c += $i->value; }, 0);
// get random
$rand = mt_rand(0, $sum);
echo $rand . " ";
// select 1st item that sum of values >= random value
$new = array_filter($arr, function ($i) use (&$rand) { if($rand > 0 && ($rand -= $i->value) <= 0) return true; else return false; });
// change key to 0
$new = array_values($new);
echo $new[0]->id;
One way to solve this is to make a list of the cummulative sum of the values in the array, for instance if the values are 3, 1, and 2 the cummulative sums would be 3, 4 and 6. Then when you want to get a random element, you generate a random integer between 1 maximum sum, and then pick the element whose cumulative sum is largest of those whos cumulative sum is smaller than or equal to the random number. In that way, the chanse of any element being picked is proportional to its value.
So here is the setup, creating the cumulative sums:
var $cumsum = array();
var $sum = 0;
foreach($array as $obj) {
$sum += $obj->value;
array_push($cumsum, $sum);
}
var $maxsum = end($cumsum);
And here is the function actually picking an element:
function getRandomObject() {
var $r = random(1, $max);
if($r < $cumsum[0]) return $array[0];
for($i = 0; $i < count($cumsum); $i++)
if($cumsum[$i]) > $r)
return $array[$i--];
return $array[$i];
}
Disclaimar: I have not tested this code, so don't expect it to run on a copy paste. Also, whatever code you use you should probably make sure it returns elements with the right probability using a monte carlo method.

PHP 3D array count unique values

I have a 3D array. I need to extract the following:
the number of occurrences of unique items in deepest level array
the number of co-occurrences of certain items in deepest level array
Array looks like this:
$arr = (
[0] => array([0] => array([flag][token][value])
[1] => array([flag][token][value])
)
)
I tried looping through the array using a for loop and an if statement, like this:
$new_arr1 = ""; // $new_arr1 = array(); //same thing, the later code doesn't work
for ($i=0; $i<count($arr);$i++)
{
for ($j=0; $j<count($arr[$i]); $j++)
{
$value= $arr[$i][$j][value];
if ($arr[$i][$j][flag] == "noun")
array_push($new_arr1, $value)
elseif ($arr[$i][$j][flag] == "verb")
array_push($new_arr2, $value)
}
}
did the same thing with switch statement, couldn't get it to work. By doing this kind of conditioning I was hoping to get all of the values from the deepest level array that meet the certain criteria into one array, and then perform *array_count_values* on them. That would give me the following:
for flag == "noun", value of value element stored in $new_arr1, and for flag == "verb", value of value element stored in $new_arr2:
$new_arr1 = (
[dog] => 7
[cat] => 2
[horse] => 4
);
$new_arr2 = (
[chase] => 2
[eat] => 5
[pwn] => 3
);
this would give me a count of unique values of the deepes level array that I can't access using *array_uniqe* function.
Besides that, I need to perform a count of co-occurrences of these values, something like this:
count the number of times that some token with certain flag comes before or after another token with a certain flag:
pseudocode:
$count=0;
if ( (($arr[$i][$j][flag] == "noun") && ($arr[$i][$j][value] == "dog")) &&
(($arr[$i][$j+/-1][flag] == "verb") && ($arr[$i][$j+/-1][value] == "chase"))
)
$count++;
$counter = array($count = array($arr[$i][$j][value]), $arr[$i][$j+/-1][value])
that would basically give the following:
counter:
array(
"7" => ([0] => "dog", [1] => "chase")
"4" => ([0] => "cat", [1] => "eat")
)
where the "7" and "4" are the names of the associative array, while "dog" and "chase" are the values stored in another array.
)
I'm not sure if I follow your question 100%, but something like this might work:
$verb_array = array();
$noun_array = array();
foreach($arr as $index => $data){
if($data['flag'] == 'noun'){
if(isset($noun_array[$data['value']])){
$noun_array[$data['value']]++;
}
else{
$noun_array[$data['value']] = 0;
}
}
else if($data['flag'] == 'verb'){
if(isset($noun_array[$data['value']])){
$verb_array[$data['value']]++;
}
else{
$verb_array[$data['value']] = 0;
}
}
}
Then to get the count of occurrences:
$noun_count = count($noun_array);
$verb_count = count($verb_array);
And if you need the count of a particular item, it will exist inside of the array.

parsing out the last number of the post

Ok so i have a post that looks kind of this
[optional_premium_1] => Array
(
[0] => 61
)
[optional_premium_2] => Array
(
[0] => 55
)
[optional_premium_3] => Array
(
[0] => 55
)
[premium_1] => Array
(
[0] => 33
)
[premium_2] => Array
(
[0] => 36 )
[premium_3] => Array
(
[0] => 88 )
[premium_4] => Array
(
[0] => 51
)
how do i get the highest number out of the that. So for example, the optional "optional_premium_" highest is 3 and the "premium_" optional the highest is 4. How do i find the highest in this $_POST
You could use array_key_exists(), perhaps something like this:
function getHighest($variableNamePrefix, array $arrayToCheck) {
$continue = true;
$highest = 0;
while($continue) {
if (!array_key_exists($variableNamePrefix . "_" . ($highest + 1) , $arrayToCheck)) {
$continue = false;
} else {
highest++;
}
}
//If 0 is returned than nothing was set for $variableNamePrefix
return $highest;
}
$highestOptionalPremium = getHighest('optional_premium', $_POST);
$highestPremium = getHighest('premium', $_POST);
I have 1 question with 2 parts before I answer, and that is why are you using embedded arrays? Your post would be much simpler if you used a standard notation like:
$_POST['form_input_name'] = 'whatever';
unless you are specifically building this post with arrays for some reason. That way you could use the array key as the variable name and the array value normally.
So given:
$arr = array(
"optional_premium_1" => "61"
"optional_premium_2" => "55"
);
you could use
$key = array_keys($arr);
//gets the keys for that array
//then loop through get raw values
foreach($key as $val){
str_replace("optional_premium_", '', $val);
}
//then loop through again to compare each one
$highest = 0;
for each($key as $val){
if ((int)$val > $highest) $highest = (int)$val;
}
that should get you the highest one, but then you have to go back and compare them to do whatever your end plan for it was.
You could also break those into 2 separate arrays and assuming they are added in order just use end() http://php.net/manual/en/function.end.php
Loop through all POST array elements, pick out elements having key names matching "name_number" pattern and save the ones having the largest number portion of the key names. Here is a PHP script which does it:
<?php // test.php 20110428_0900
// Build temporary array to simulate $_POST
$TEMP_POST = array(
"optional_premium_1" => array(61),
"optional_premium_2" => array(55),
"optional_premium_3" => array(55),
"premium_1" => array(33),
"premium_2" => array(36),
"premium_3" => array(88),
"premium_4" => array(51),
);
$names = array(); // Array of POST variable names
// loop through all POST array elements
foreach ($TEMP_POST as $k => $v) {
// Process only elements with names matching "word_number" pattern.
if (preg_match('/^(\w+)_(\d+)$/', $k, $m)) {
$name = $m[1];
$number = (int)$m[2];
if (!isset($names[$name]))
{ // Add new POST var key name to names array
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
} elseif ($number > $names[$name]['max_num'])
{ // New largest number in key name.
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
}
}
}
print_r($names);
?>
Here is the output from the script:
Array
(
[optional_premium] => Array
(
[name] => optional_premium
[max_num] => 3
[key_name] => optional_premium_3
[value] => Array
(
[0] => 55
)
)
[premium] => Array
(
[name] => premium
[max_num] => 4
[key_name] => premium_4
[value] => Array
(
[0] => 51
)
)
)
Though ineffective, you could try something like
$largest = 0;
foreach($_POST as $key => $value)
{
$len = strlen("optional_premium_");
$num = substr($key, $len);
if($num > $largest)
$largest = $num;
}
print_r($largest);
The problem being that this will only work for one set of categories. It will most likely give errors throughout the script.
Ideally, you would want to reorganize your post, make each array be something like
[optional_premium_1] => Array
(
[0] => 61
["key"] => 1
)
[optional_premium_2] => Array
(
[0] => 61
["key"] => 2
)
Then just foreach and use $array["key"] to search.

Categories