There are tons of mutli dimensional array.
I want to judge last key in multi dimensional array grouping by one of the value.
SO,...
$i=0;
$j=0;
$limit=10;
$huge_arr = array(
array("point" => 20
"os" => "iOS"),
array("point" => 5
"os" => "iOS"),
array("point" => 10
"os" => "Android"),
array("point" => 20
"os" => "Android"),
array("point" => 7
"os" => "iOS"),
array("point" => 3
"os" => "Android"),
/*... tons of array..*/
);
foreach($huge_arr as $k => $v)
{
if($v['os'] === "iOS")
{
$i++;
if($i % $limit ===0 )
{
//Do something By $limit count :#1
}
//TO DO
//#Q:WANT TO DO same thing when there aren't $v['os'] === "iOS" in rest of $array
}
else if($v['os'] === "iOS")
{
$j++;
if($j % $limit ===0 )
{
//Do something By $limit count :#2
}
//TO DO
//#Q:WANT TO Do same thing when there aren't $v['os'] === "Android" in rest of $array
}
}
So I do not want to do that. this way is NG
foreach($huge_arr as $k => $v)
{
if($v['os'] === "iOS")
{
$ios[] = $v["point"];
}else if($v['os'] === "Android")
{
$ad[] = $v["point"];
}
}
$ios_count = count($ios);
$ad_count = count($ad);
foreach($ios as $k => $v)
{
if($k === $ios_count -1)
//do something for last value
}
foreach($ad as $k => $v)
{
if($k === $ad_count -1)
//do something for last value
}
Does anyone know smart way....
This does not require createing new arrays but rather just takes what you need from the array - assuming you will only need the last IOS and android key.
$ios_key = $ad_key = NULL; // If one of them is not present key will be NULL
// Reverse the array to put the last key at the top
array_reverse($huge_arr);
foreach($huge_arr as $k => $v)
{
// Fill key with ios key value if not already set
if($v['os'] === "iOS" AND $ios_key === NULL)
{
$ios_key = $k;
}
// Fill key with first android key value if not already set
else if($v['os'] === "Android" AND $ad_key === NULL)
{
$ad_key = $k;
}
// Stop looping when we found both keys
if($ios_key !== NULL AND $ad_key !== NULL)
break;
}
// Put the array back in original order
array_reverse($huge_array);
// Do whatever you want with the array now
For the other part of your question do the same thing when there aren't IOS ....
if($i % $limit ===0 )
into
if($i % $limit === 0 OR $k === $ios_key) // $ios_key should be the last key
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.