Jump to content

How to find the key of a sub array within a multidimensional array by matching a value


PHP Learner

Recommended Posts

Hi all,

 

This seems like it should be really simple but to me it's not. I have an array in a variable called $numbers. When I run print_r ($numbers) I get the following...

$earchForNumber = '0304';

// Array called $numbers 

Array 
(
[0] => Array ( [0] => 0219, 0220, 0221, 0222, 0223 )

[1] => Array ( [0] => 0301, 0302, 0303, 0304 ) 

[2] => Array ( [0] => 1230, 1231, 0101, 0102 )
)

if (in_array($earchForNumber, $numbers)) {echo 'The key is' . $key;}


What I need to do is search for a number within all of the sub arrays and find the key which it belongs to. So if I wanted to find the key for the value of $earchForNumber (0304) it would return a key of 1.

 

There are tons of posts on stack overflow about this sort of thing but I can't find any that perform this task. I played around with inarray() but couldn't get any joy.

 

Any ideas?

 

 

Link to comment
Share on other sites

Your array doesn't make sense. If you have posted it correctly, the sub-arrays contain one element that consists of a single value. And that value is a comma separated string? If that is the case you don't need a multi-dimensional array. Although, what you should have is a multi-dimensional array with multiple elements in the sub array, such as this:

 

 

Array 
(
[0] => Array ( [0] => 0219, [1] => 0220, [2] => 0221, [3] => 0222, [4] => 0223 )

[1] => Array ( [0] => 0301, [1] => 0302, [2] => 0303, [3] => 0304 ) 

[2] => Array ( [0] => 1230, [1] => 1231, [2] => 0101, [3] => 0102 )
)

 

So, please verify what you have

Link to comment
Share on other sites

If you have the array built correctly (as I showed), this should work

function subarray_search($array, $searchValue)
{
    foreach($array as $parentKey => $subarray)
    {
        if(in_array($searchValue, $subarray))
        {
            //If found, return parent key
            return $parentKey;
        }
    }
    //Not found, return false
    return false;
}


//Usage
$key = subarray_search($array, 0304);

//Note: Be sure to EXPLICITLY test for FALSE
//      an index of 0 can be interpreted as
//      false if not compared correctly

if($key === false) //Note three equal signs
{
    echo "The Value was not found";
}
else
{
    echo "The value was found in key {$key}";
}
Edited by Psycho
Link to comment
Share on other sites

Yep your absolutely right Psycho. The numbers are actually dates (month and day) which I need for something. They exist in a row which has a start date and a finish date column (amongst others) and I have had to fill in the dates in between. I'm gonna post the code here, it's probably a bit shite but anyway. What I need to do is compare an inputted date with a value in the array and find the key which reffers to the row (rowNo) it came from. Not sure if that makes much sense to you or not, anywayz tha code.

 

 

rowNo | startDate | finishDate | other columns

 

1         |    0301    |     0304     |      stuff

    while($row = mysql_fetch_array($grabDates)) {
            
        $startDate = $row['startDate'];
        $finishDate = $row['finishDate'];
        $rowNo = $row['rowNo'];
        
        $arrayDate = $startDate;
    
        $break = '';
    
    
        while($break !== 'something') {
            
        if ($break == 'break') {$arrayEntry .= $arrayDate;} else {$arrayEntry .= $arrayDate . ', ';}
        
        if ($break == 'break') {$break = ''; $arrayDate = ''; break;}
        
        if ($arrayDate == '1231') {$arrayDate = '0101';} else {$arrayDate++;}
        
        $countDateString = strlen($arrayDate);
        
        if ($countDateString == '3') {$arrayDate = '0' . $arrayDate;}
        
        if ($arrayDate == $finishDate) {$break = 'break';}
        
        }
     
        $numbers[] = array($arrayEntry);
        
         $arrayEntry = '';
        
    } // End - while($row = mysql_fetch_array($grabDates)) {

So I'm trying to build the array with key value pairs with a string seperated by commas in each key. Roughly something like this...

 

 

Array

 

[0] => (1234, 5678, 9012, 3456)

 

[1] => (3456, 9012, 5678, 1234)

 

[2] => (1234, 5678, 9012, 3456)

 

etc...

Edited by PHP Learner
Link to comment
Share on other sites

If this is in a database, why are you putting this logic in the PHP code? And, why would you put multiple values into a single string like that. Makes it difficult to manipulate data - as you are now finding.

 

I'm having trouble following your logic, but it seems you are creating an array of all dates between the start date and the end date. I hope you are storing the values as actual dates and not strings. Anyway, I would create the array with just two values for the start date and the finish date. Then create logic to see if the date you are testing is between those two dates. I would not run a process to determine each day in the range until you need to output them.

 

The logic, as it is now won't work across months. E.g. When it comes to the date March 31 it will be 0331. Then when you add 1 it will be 0332 - an invalid date.

Link to comment
Share on other sites

Yep it's flawed isn't. Ok back to the drawing board, so I know how to grab the date BETWEEN start and finsh dates in a mysql query, but how do you grab all dates from all the rows in one query and crank them out into an array which can be used to find the row it came from to gather the rest of the data?

 

 

Link to comment
Share on other sites

if you post just an example, showing some sample database rows, what your input is (what $earchForNumber comes from and is it going to be one value at a time or are you actually doing this for a whole month of days or what), and what result you are trying to produce from that input and the data, it will be much easier to help you.

 

also, for anything like an event/booking schedule, you would need the year stored as part of the date to avoid ambiguous results at the end/start of years and once you have data for more than one year.

Link to comment
Share on other sites

Yep it's flawed isn't. Ok back to the drawing board, so I know how to grab the date BETWEEN start and finsh dates in a mysql query, but how do you grab all dates from all the rows in one query and crank them out into an array which can be used to find the row it came from to gather the rest of the data?

 

That's the problem. There is no need to process the begin and end dates into an array of all the days - just to find out if a certain date is included in them. You can do that very simply with a single query.

$targetDate = '2014-03-05';
 
//Find all records where $targetDate is contained in the
//period from startDate to finishDate
$query = "SELECT id FROM some_table WHERE '$targetDate' BETWEEN startDate AND finishDate

Don't explode the startDate and finishDate into individual days for the purpose of performing any logic on them. There are way better ways to do that programatically. Only extract into the individual days when generating the output.

Edited by Psycho
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.