This is a more complicated example, but better than spaghetti code. Turn your array into XML first.
// this is your initial array
$my_array = array(
array("city"=>309, "store"=>12, "apples"=>21, "oranges"=>14, "lichis"=>34 ),
array("city"=>309, "store"=>13, "apples"=>0, "oranges"=>11, "lichis"=>32 ),
array("city"=>309, "store"=>14, "apples"=>44, "oranges"=>61, "lichis"=>0 ),
array("city"=>309, "store"=>15, "apples"=>7, "oranges"=>0, "lichis"=>6 ),
array("city"=>309, "store"=>16, "apples"=>0, "oranges"=>0, "lichis"=>12 ),
);
Writing spaghetti code to manually isolate stores becomes a messy jungle of if statements and loops.
// might as well convert it to xml
function array_to_xml( $data ) {
$xml = "<xml>\n";
foreach( $data as $row ) {
$xml .= "<entry>";
foreach( $row as $k => $v ) {
$xml .= "<{$k}>{$v}</{$k}>";
}
$xml .= "</entry>\n";
}
$xml .= "</xml>\n";
return( $xml );
}
At this point, $xml
looks like this (as a string) and is more manageable:
<xml>
<entry>
<city>309</city>
<store>12</store>
<apples>21</apples>
<oranges>14</oranges>
<lichis>34</lichis>
</entry>
...(more entries)...
</xml>
Now, load it into something queriable with XPath, an XML standard:
$xml = simplexml_load_string( array_to_xml( $my_array ) );
To get the count of all the specific fruits in the city (i.e. how many apples, oranges, lichies are there in total in city 309) we need a simple but reusable summary function.
// so lets make a generic function to count specific items
function count_items( $stores, $items = array() ) {
$sum = array();
foreach( $stores as $store ) {
foreach( $items as $k ) {
if( !isset( $sum[$k] ) ) $sum[$k] = 0;
$sum[$k] += $store->$k;
}
}
return( $sum );
}
We only want city 309, and looking specifically for apples, oranges and lichis, since they are fruits:
$only_this_city = $xml->xpath("//entry[city=309]");
print_r( count_items( $only_this_city, array("apples", "oranges", "lichis")) );
We get this:
Array
(
[apples] => 72
[oranges] => 86
[lichis] => 84
)
Secondly, to grab the values for a specific store:
$only_this_store = $xml->xpath("//entry[city=309 and store=14]");
print_r( count_items( $only_this_store, array("apples") ) );
You get:
Array
(
[apples] => 44
)
Obviously you can request more items, or query with more complexity. Look up some docs on XPath for future queries.