I will have set of array which comes in the form like this
<?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)
) ?>
For index [1] and index[3], the "value" is not set. I would like to take these two array and arrange at the end of the array. In the end, the result would be like this in the below..
<?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)
) ?>
So, I need to check whether name "value" exist in the array using looping, if it is not exist , it would need to be transferred to the end of the the array. How to perform this movement?
Please help.
Loop through the array and check if each sub-array has a value
element. If it doesn't, push it to $monthsWithoutIndices
. If it does, push it to $monthsWithIndices
. Once the looping is over, join these two arrays together using array_merge()
to obtain the final result:
$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);