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.
精彩评论