Jamshaid Sabir
Jamshaid Sabir

Reputation: 73

Assign Specific key to Array Elements

I have an array as follows :-

$alldatesandtimes = ["2016-10-04 00:00:01","2016-10-04 23:59:59","2016-10-05 00:00:01","2016-10-05 23:59:59","2016-10-06 00:00:01","2016-10-06 23:59:59"]

I want to assign datein as the index of first element and dateout to 2nd element. Then datein as the index of 3rd element and dateout to 4th element and so on and so forth to all the remaining elements.

so first index shall be datein and 2nd index shall be dateout then keep on upto the last element.

I have following code :-

$keys = array();
$result = array();
for($j=0; $j<((sizeof($alldatesandtimes))/2); $j++)
{
  $keys[] = "datein";
  $keys[] = "dateout";
}//end for loop

for($i = 0; $i< sizeof($alldatesandtimes); $i++)
{
  $result[][$keys[$i]] =$alldatesandtimes[$i];
}

it returns the following array :-

$result = Array ( [0] => Array ( [datein] => 2016-10-04 00:00:01 ) [1] => Array ( [dateout] => 2016-10-04 23:59:59 ) [2] => Array ( [datein] => 2016-10-05 00:00:01 ) [3] => Array ( [dateout] => 2016-10-05 23:59:59 ) [4] => Array ( [datein] => 2016-10-06 00:00:01 ) [5] => Array ( [dateout] => 2016-10-06 23:59:59 ) )

but i want

$result = ['datein' => '2016-10-04 00:00:01', 'dateout' => '2016-10-04 23:59:59', 'datein' => '2016-10-05 00:00:01', .....

Kindly help me?

Upvotes: 0

Views: 42

Answers (3)

user2047029
user2047029

Reputation:

You can loop the array with incrementing the $i variable by two ( $i+2). This way you all get every second element. after that assign a new array to another array as follows

$result[]=array("datein"=>$arr[$i], "dateout" => $arr[$i+1]);

Upvotes: 0

Robert Parham
Robert Parham

Reputation: 704

Not nearly as fancy as abra's answer but...

$newDates = array();
$dateHolder = array();
foreach($alldatesandtimes as $k=>$v){
    $key = $k%2===0 ? "dateIn" : "dateOut";
    $newDates[$key] = $v;
    if(count($newDates)===2){
        $dateHolder[] = $newDates;
        $newDates = array();
    }
}
$alldatesandtimes = $dateHolder;

https://3v4l.org/BCoYd

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78984

You can chunk it into pairs and then combine the value pairs with the key pair:

foreach(array_chunk($alldatesandtimes, 2) as $pair) {
    $result[] = array_combine(['datein', 'dateout'], $pair);
}

Upvotes: 3

Related Questions