How to create an associative array in following case? - php

I'm having few arrays as follows. Actually I'm having too many such arrays but for your reference I've printed only few of them:
Array
(
[0] => lineItemData
[1] => name
)
Array
(
[0] => lineItemData
[1] => startDate
)
Array
(
[0] => lineItemData
[1] => endDate
)
Array
(
[0] => lineItemData
[1] => frequencyCapping
[2] => interval
)
Array
(
[0] => lineItemData
[1] => frequencyCapping
[2] => amount
)
Array
(
[0] => orderId
)
Array
(
[0] => isExternal
)
Now you can observe in man of the above arrays key value [lineItemData] is common and it is present at oth index. Now I want to create a new array where the key would be [lineItemData] and other arrays which don't have a value [lineItemData] present within themselves should be new keys and other keys should be keys under every key. My question may confuse you. So I'm printing below the desired output array
Array
(
[lineItemData] => Array
(
[name] =>
[startDate] =>
[endDate] =>
[frequencyCapping] => Array
(
[interval] =>
[amount] =>
)
)
[orderId] =>
[isExternal] =>
)

You can do this with:
$data = [
['lineItemData', 'name'],
['lineItemData', 'startDate'],
['lineItemData', 'endDate'],
['lineItemData', 'frequencyCapping', 'interval'],
['lineItemData', 'frequencyCapping', 'amount'],
['orderId'],
['isExternal']
];
$result = [];
$pointer = &$result;
foreach($data as $keys)
{
foreach($keys as $key)
{
if(is_array($pointer) && !array_key_exists($key, $pointer))
{
$pointer[$key] = null;
}
$pointer = &$pointer[$key];
}
$pointer = &$result;
}
End result will look like:
array(3) {
["lineItemData"]=>
array(4) {
["name"]=>
NULL
["startDate"]=>
NULL
["endDate"]=>
NULL
["frequencyCapping"]=>
array(2) {
["interval"]=>
NULL
["amount"]=>
NULL
}
}
["orderId"]=>
NULL
["isExternal"]=>
NULL
}

Maybe like so?
<?php
$super['lineItemData']['name'] = NULL;
$super['lineItemData']['startDate'] = NULL;
$super['lineItemData']['endDate'] = NULL;
$super['lineItemData']['frequencyCapping']['interval'] = NULL;
$super['lineItemData']['frequencyCapping']['amount'] = NULL;
$super['orderId'] = NULL;
$super['isExternal'] = NULL; ?>
I'm sure someone will get crafty and find a way to make this happen in one array statement. I like this because it's easier for me to manage.

Related

How to remove specific element from array in php

I have the following array
Array
(
[tags] => Array
(
[0] => hello
)
[assignee] => 60b6a8a38cf91900695dd46b
[multiple_assignee] => Array
(
[0] => Array
(
[accountId] => 60b6a8a38cf91900695dd46b
)
[1] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
)
I want to remove 60b6a8a38cf91900695dd46b from the multiple_assignee array.
I have tried with the following code:
if (($key = array_search($this->getUsersHashMapValue($responsiblePartyIds[0]), $mutipleAssignee)) !== false) {
unset($mutipleAssignee[$key]['accountId']);
}
But it is not removing that element. The intention is I don't want to repeat the 60b6a8a38cf91900695dd46b assignee in the multiple assignee array.
I have also tried with the following code:
foreach($mutipleAssignee as $subKey => $subArray){
if($subArray['accountId'] == $this->getUsersHashMapValue($responsiblePartyIds[0])){
unset($mutipleAssignee[$subKey]);
}
}
But it is resulting as
Array
(
[tags] => Array
(
[0] => hello
)
[assignee] => 60b6a8a38cf91900695dd46b
[multiple_assignee] => Array
(
[1] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
)
rather than
[multiple_assignee] => Array
(
[0] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
Thank you
Just extract the accountId column and search that. Then use that key:
$key = array_search($this->getUsersHashMapValue($responsiblePartyIds[0]),
array_column($mutipleAssignee, 'accountId'));
unset($mutipleAssignee[$key]);
After your edit it seems you just want to reindex the subarray after unset:
$mutipleAssignee = array_values($mutipleAssignee);
I would just use a simple for loop. All of the array_* functions are really helpful but I find that they hide nuances. Since I don't have your functions I'm just making a plain-old one, but you should be able to port this.
$data = [
'tags' => [
'hello',
],
'assignee' => '60b6a8a38cf91900695dd46b',
'multiple_assignee' => [
[
'accountId' => '60b6a8a38cf91900695dd46b',
],
[
'accountId' => '5b39d23d32e26a2de15f174f',
],
],
];
$assignee = $data['assignee'];
foreach ($data['multiple_assignee'] as $multiple_assignee_key => $multiple_assignee) {
// if the root assignee is also listed in the multiple assignee area
if ($multiple_assignee['accountId'] === $assignee) {
// remove the duplicate from the multiple area
unset($data['multiple_assignee'][$multiple_assignee_key]);
// re-index the array
$data['multiple_assignee'] = array_values($data['multiple_assignee']);
}
}
This outputs:
array(3) {
["tags"]=>
array(1) {
[0]=>
string(5) "hello"
}
["assignee"]=>
string(24) "60b6a8a38cf91900695dd46b"
["multiple_assignee"]=>
array(1) {
[0]=>
array(1) {
["accountId"]=>
string(24) "5b39d23d32e26a2de15f174f"
}
}
}
Demo here: https://3v4l.org/tYppK

How to move a value up to a key, and remove a key. Array manipulation

I'm trying to change my array from this:
Array
(
[0] => Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
)
)
[1] => Array
(
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
[2] => Array
(
[BID_OPEN] => Array
(
[0] => 1.654878
)
)
)
in to this:
Array
(
[BID_OPEN]
(
[0] => 0.718282
[1] => 1.654878
)
[BID_CLOSE]
(
[0] => 1.654545
[1] => 1.645845
)
)
I'm not sure how to begin. My code:
foreach($array as $keys=>$values)
{
if(!empty($array [$c]['BID_OPEN']))
{
$inital_part1 = array("BID_OPEN", $array [$c]['BID_OPEN']);
}
else
{
echo '';
}
if(!empty($array [$c]['BID_CLOSE']))
{
$inital_part2 = array("BID_CLOSE", $array [$c]['BID_CLOSE']);
}
else
{
echo '';
}
$array1[] = $inital_part1;
$array1[] = $inital_part2;
$c++;
}
I seem to get double outputs, so the foreach when I build arrays is giving me two times the required output. Google reckons it's because I have an array in my array somewhere but I'm precisely sure I don't.
The array came from an object stdclass and I don't know what that is, have googled but haven't found anything useful. Also I'm able to get some figures but only the initial values are correct, the rest of the data doesn't seem to come through. No doubt it's because I used an index[0] to get it working.
After hours any help would be great thanks.
As long as you have told us everything about your input array it can be done quite simply like this
<?php
$in = [ ['BID_OPEN' => [0.718282]],
['BID_CLOSE' => [1.654545]],
['BID_OPEN' => [1.654878]]
];
print_r($in);
$new = []; // new array we are building
foreach ($in as $abid) {
if (array_key_exists('BID_OPEN', $abid) ) {
$new['BID_OPEN'][] = $abid['BID_OPEN'][0];
}
if (array_key_exists('BID_CLOSE', $abid) ) {
$new['BID_CLOSE'][] = $abid['BID_CLOSE'][0];
}
}
print_r($new);
THE INPUT ARRAY: Is like yours
Array
(
[0] => Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
)
)
[1] => Array
(
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
[2] => Array
(
[BID_OPEN] => Array
(
[0] => 1.654878
)
)
)
RESULT:
Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
[1] => 1.654878
)
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
$c = 0;
$array1['BID_OPEN'] = [];
$array2['BID_CLOSE'] = [];
foreach($vartttttt as $tunips=>$ert)
{
$d = 0;
foreach($ert as $erts=>$val)
{
//$array[] = $erts;
if($erts == 'BID_OPEN')
{
array_push($array1['BID_OPEN'], $val[0]);
}
if($erts == 'BID_CLOSE')
{
array_push($array2['BID_CLOSE'], $val[0]);
}
$d++;
}
$c++;
}
$array = array_merge($array1, $array2);

Pushing a sub array into the same array

I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>

Convert complex numerical array to associative array

I have an array data that look like this :
Array (
[0] => Array (
[0] => Name:
[1] => John W.
[2] => Registration ID:
[3] => 36
)
[1] => Array (
[0] =>Age:
[1] => 35
[2] => Height:
[3] => 5'11"
)
[3] => Array (
[0] => Sex:
[1] => M
[2] => Weight:
[3] => 200lbs
)
[4] => Array (
[0] => Address
)
[5] => Array (
[0] => 6824 crestwood dr delphi, IN 46923
))
And I want to convert it to associative array like this :
Array(
['Name']=> John W.
['Registration ID']=> 36
['Age']=> 35
['Height'] => 5'11''
['Sex']=>M
['Weight']=>200lbs
['Address']=>6824 crestwood dr delphi, IN 46923
)
I have no idea at all how to do this, since the supposed to be array column header were also in sequence, so it makes difficult to convert this array.
Any help I appreciate, thx.
Given your origin array is called $origin , you can do it like this:
$merged = array();
foreach($origin as $val) {
$merged = array_merge($merged, $val);
}
$tot = count($merged) - 1;
for ($i=0;$i<$tot;$i+=2) {
$result[$merged[$i]] = $merged[$i+1];
}
var_dump($result); // To test the resulting array
Firstly, I use array_merge() to flatten the $origin array to only one dimension/depth, so we later iterate it (stepping each 2 items per iteration) and assigning each pair of items ($i and $i+1) to the resulting array.
Looks like, for the first 3 children, you can just assign the even value to the previous element as key. Then, assign the fourth one as key for fifth element.
$result = array();
foreach ($array as $key => $value)
{
if ($key < 4) {
$elements = array_values($value);
$result[$elements[0]] = $elements[1];
$result[$elements[2]] = $elements[3];
}
if ($key == 4)
$fifthkey = $value;
if ($key == 5)
$result[$fifthkey] = $value;
}
Also, note that you have to escape your height string quotes.

sorting a php array

how do i sort this array by the nums...
Array(
[nums] => Array
(
[0] => 34
[1] => 12
[2] => 13
)
[players] => Array
(
[0] => Mike
[1] => Bob
[2] => Mary
)
)
... so that i get this one?
Array(
[nums] => Array
(
[0] => 12
[1] => 13
[2] => 34
)
[players] => Array
(
[0] => Bob
[1] => Mary
[2] => Mike
)
)
array_multisort($x['nums'],$x['players']);
Try the sort function.
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
Also check out asort and arsort
EDIT
I did not take into account your Multidimensional array.
<?php
//code derived from comments on the php.net/sort page.
// $sort used as variable function--can be natcasesort, for example
function sort2d( &$arrIn, $index = null, $sort = 'sort') {
// pseudo-secure--never allow user input into $sort
if (strpos($sort, 'sort') === false) {$sort = 'sort';}
$arrTemp = Array();
$arrOut = Array();
foreach ( $arrIn as $key=>$value ) {
reset($value);
$arrTemp[$key] = is_null($index) ? current($value) : $value[$index];
}
$sort($arrTemp);
foreach ( $arrTemp as $key=>$value ) {
$arrOut[$key] = $arrIn[$key];
}
$arrIn = $arrOut;
}
?>

Categories