I'm trying to loop through a multidimensional array, whereby, if a condition is matched, all elements of that array should be stored into a new array named after the condition it matched.
$unique_states = array_unique($allstates);
$total = count($states);
for($i = 0; $i < $total; $i++){
foreach($unique_states as $keys => $values){
if(($states[$i][3] == $values)){
$values[] = $states[$i];
}
}
}
$states
is the mega array that contains everything. When I loop through the array so that if this condition if(($states[$i][3] == $values))
is matched, a new array should be created with the name of $values
.
When I run the code and print_r($values)
, I get Fatal error: [] operator not supported for strings
. When I change the name to something totally different, I simply get all the array in $states
.
Not sure how to do this anymore.
Edit:
When I remove the foreach
loop and insert the actual values of $values
like this
if(($states[$i][3] == 'state1')){
$states1[] = $states[$i];
}
if(($states[$i][3] == 'state2')){
$states2[] = $states[$i];
}
it works very well. But in a case where I have several states, the code above will not be efficient enough and will require that I make changes each time a new state is added. I need to return an array of the whole elements..i.e $states[$i] for which $states[$i][3] matched.
Example of data from $states input:
Array
(
[0] => Array
(
[0] => firstname1
[1] => lastname1
[2] => Armstrong Landscaping
[3] => state1
[4] => email1
[5] => address1
)
[1] => Array
(
[0] => firstname2
[1] => lastname2
[2] => Armstrong Landscaping
[3] => state1
[4] => email2
[5] => address2
)
[2] => Array
(
[0] => firstname3
[1] => lastname3
[2] => Armstrong Landscaping
[3] => state1
[4] => email3
[5] => address3
)
[3] => Array
(
[0] => firstname4
[1] => lastname4
[2] => Cannon Heathcare Center
[3] => state2
[4] => email4
[5] => address4
)
[4] => Array
(
[0] => firstname5
[1] => lastname5
[2] => Cannon Heathcare Center
[3] => state2
[4] => email5
[5] => address5
)
Example out put should look something like this
Array
(
[state1] => Array
(
[0] => Array
(
[0] => firstname1
[1] => lastname1
[2] => Armstrong Landscaping
[3] => state1
[4] => email1
[5] => address1
)
[1] => Array
(
[0] => firstname2
[1] => lastname2
[2] => Armstrong Landscaping
[3] => state1
[4] => email2
[5] => address2
)
Array
(
[state2] => Array
(
[0] => Array
(
[0] => firstname1
[1] => lastname1
[2] => Armstrong Landscaping
[3] => state2
[4] => email1
[5] => address1
)
[1] => Array
(
[0] => firstname2
[1] => lastname2
[2] => Armstrong Landscaping
[3] => state2
[4] => email2
[5] => address2
)