Checking awkward array
I have an array that looks like following.
$ => Array (2)
(
| ['0'] => Array (2)
| (
| | ['0'] = String(1) "2"
| | ['1'] = String(1) "2"
| )
| ['1'] => Array (2)
| (
| | ['0'] = String(1) "2"
| | ['1'] = String(1) "1"
| )
)
But could also be bigger or smaller having only one array.
Each array represents a row of result that have been returned from a database.
The first field [0][0] is a ID number which is going to be needed.
[0][1] is the value I need to check.
I need to know whether it is present or not, say whether I got a 2 or a 1 or whether I didn't.
If I didn't then I need to send the ID ([0][0]) off to another function.
Sometimes I may end up with more results or less. So this needs to be done using loops but am struggling to get it right, each time I think I have some code that will work it won't.
Can anyone help out?
Edit:
This is what I g开发者_运维百科ot so far...
$tweet_sentiment = array();
$analyzer = array();
foreach($get_sentiment as $sentiment) {
$tweet_id = $sentiment[0];
$analyzer[] = $sentiment[1];
$tweet_sentiment[$tweet_id] = $analyzer;
}
This changes the way the arrays look into the following:
$ => Array (1)
(
| ['2'] => Array (2)
| (
| | ['0'] = String(1) "2"
| | ['1'] = String(1) "1"
| )
)
This is how I understand your question.
A first loop goes through the main array and works on its index => array2.
The 2nd loop goes through that second array and check if the value of that array is "value1". If it is, it executes doWhenValueIsThere()
otherwise it executes doWhenValueIsNotThere()
.
You have to create the two functions depending on your needs.
foreach ($array1 as $index => $array2)
{
foreach (array_keys($array2) as $id)
{
if ($array2[$id] == "value1") doWhenValueIsThere();
else doWhenValueIsNotThere();
}
}
Maybe you can do the check like this:
array_key_exists(1, $x[1]) ? $x[1][1] : otherFunction($x[0][0])
where $x is your array.
try this
<?php
$tweet_sentiment = array();
$analyzer = array();
foreach($get_sentiment as $sentiment) {
$tweet_id = $sentiment[0];
if(isset($sentiment[1])){
$analyzer[] = $sentiment[1];
$tweet_sentiment[$tweet_id] = $analyzer;
}
}
?>
I ended up changing a few of the internal SQL statements so that my result from the database was different.
I found that the SQL statements I were using and the returned arrays were too complex to process in the way I wanted - mainly due to how it was formatted by the SQL query results.
精彩评论