如何通过数组搜索我的索引并找到匹配项,然后将其移动到php中的最后一个索引


How to search through my index through the array and find the match then move it to the last index in php?

我将有一组数组,其形式如下

<?php
$month = array(
[0]=>array("title"=>"Jan",
"key"=>1,
"value"=>1),
[1]=>array("title"=>"Feb",//index "value" not set
"key"=>1
),
[2]=>array("title"=>"March",
"key"=>1,
"value"=>1),
[3]=>array("title"=>"Apr", //index "value" not set
"key"=>1
),
[4]=>array("title"=>"May",
"key"=>1,
"value"=>1),
[5]=>array("title"=>"June", 
"key"=>1,
"value"=>1)
) ?>

对于索引[1]和索引[3],不设置"值"。我想把这两个数组放在数组的末尾。最后,结果如下。。

<?php
//Desired Result
$months = array(
[0]=>array("title"=>"Jan",
"key"=>1,
"value"=>1),
[1]=>array("title"=>"March",
"key"=>1,
"value"=>1),
[2]=>array("title"=>"May",
"key"=>1,
"value"=>1),
[3]=>array("title"=>"June",
"key"=>1,
"value"=>1),
[4]=>array("title"=>"Feb",  //the without "value" will be changed to here
"key"=>1),
[5]=>array("title"=>"Apr", //the without "value" will be changed to here
"key"=>1)
) ?>

所以,我需要使用循环检查名称"value"是否存在于数组中,若不存在,则需要将其转移到数组的末尾。如何进行这个动作?

请帮忙。

循环遍历数组并检查每个子数组是否有一个value元素。如果没有,则将其推送到$monthsWithoutIndices。如果是,则将其推送到$monthsWithIndices。循环结束后,使用array_merge()将这两个数组连接在一起,以获得最终结果:

$monthsWithIndices = array();
$monthsWithoutIndices = array();
foreach ($month as $key => $arr) 
{
    if (!isset($arr['value'])) 
    {   // If it doesn't have a 'value'
        $monthsWithoutIndices[] = $arr;
    } 
    else 
    {   // If it has a 'value'
        $monthsWithIndices[] = $arr;
    }
}
// Join the two arrays
$result = array_merge($monthsWithIndices, $monthsWithoutIndices);

演示