how can I find value in sub multidimensional array? - php

I have this array:
Array ( [0] => Array ( [asset] => track [path] => media/promenade_web/AUDIO/promenade-arkadiev.mp3 [file_name] => promenade-arkadiev [permission_audio_play_synchronization] => Array ( [synchronization] => Array ( [constraint] => Array ( [numberOfMeasures] => Array ( [startMeasure] => 1 [number] => 10 ) [qualityOfResource] => medium ) [requirement] => Array ( ) [condition] => Array ( ) ) [play] => Array ( [constraint] => Array ( [numberOfMeasures] => Array ( [startMeasure] => 1 [number] => 10 ) [qualityOfResource] => medium [spatial] => iso3166:CH,IT [count] => 10 [datetime] => Array ( [start] => 2017-08-16 [end] => 2017-10-20 ) [accumulated] => P30D [format] => mp3,wav ) [requirement] => Array ( ) [condition] => Array ( ) ) ) ) [1] => Array ( [asset] => track [path] => media/promenade_web/AUDIO/promenade-arkadiev_lo.mp3 [file_name] => promenade-arkadiev_lo [permission_audio_play_synchronization2] => Array ( [play] => Array ( [constraint] => Array ( [numberOfMeasures] => Array ( [startMeasure] => 1 [number] => 10 ) [qualityOfResource] => medium [spatial] => iso3166:CH,IT [count] => 10 [datetime] => Array ( [start] => 2017-08-16 [end] => 2017-10-20 ) [accumulated] => P30D [format] => mp3,wav ) [requirement] => Array ( [prepay] => Array ( [amount] => 0.99 [currency] => EUR ) ) [condition] => Array ( ) ) ) ) )
How can I find a value with foreach, regardless of the number of subarrays?
I've tried with this code, but it doesn't work:
function recursive_array_search($needle, $haystack, $currentKey = '') {
foreach($haystack as $key=>$value) {
if (is_array($value)) {
$nextKey = recursive_array_search($needle,$value, $currentKey . '[' . $key . ']');
if ($nextKey) {
return $nextKey;
}
}
else if($value==$needle) {
return is_numeric($key) ? $currentKey . '[' .$key . ']' : $currentKey;
}
}
return false;
}

I always use following on multi dimensional array
$arr = array(array('id'=>1,'name'=>'nilesh'),array('id'=>2,'name'=>'ajay'));
echo "<pre>";
print_r($arr[array_search('nilesh', array_column($arr,'name'))]);
echo "</pre>";

Related

PHP Looping over Nested Array [duplicate]

This question already has answers here:
PHP Getting Values From Nested Array
(2 answers)
Closed last year.
I have an array which looks like this:
Array
(
[response] => Array
(
[dataInfo] => Array
(
[totalRecordCount] => 362
[foundCount] => 5
[returnedCount] => 5
)
[data] => Array
(
[0] => Array
(
[fieldData] => Array
(
[groupAssetID] => 1020
[groupAssetName] => Standard Equipment
)
[portalData] => Array
(
)
[recordId] => 823
[modId] => 1
)
[1] => Array
(
[fieldData] => Array
(
[groupAssetID] => 1001
[groupAssetName] => Tools
)
[portalData] => Array
(
)
[recordId] => 829
[modId] => 1
)
[2] => Array
(
[fieldData] => Array
(
[groupAssetID] => 1005
[groupAssetName] => Spare Parts
)
[portalData] => Array
(
)
[recordId] => 830
[modId] => 1
)
)
)
[messages] => Array
(
[0] => Array
(
[code] => 0
[message] => OK
)
)
)
I'm trying to loop over this and extract the values for groupAssetID and groupAssetName in the data array but haven't been able to get this to work so far. I've tried:
foreach ( $records as $record) {
echo $field . ": " . $value . "<br />\r\n" ;
}
and
foreach ( $records->fieldData as $field=>$value) {
echo $field . ": " . $value . "<br />\r\n" ;
}
but none of these seem to work and I can't work out the correct syntax here.
I managed it to run with this syntax:
$records = array
(
'response' => array
(
'dataInfo' => array
(
'totalRecordCount' => 362,
'foundCount' => 5,
'returnedCount' => 5
),
'data' => array
(
0 => array
(
'fieldData' => array
(
'groupAssetID' => 1020,
'groupAssetName' => 'Standard Equipment'
),
'portalData' => array
(
),
'recordId' => 823,
'modId' => 1
),
1 => array
(
'fieldData' => array
(
'groupAssetID' => 1001,
'groupAssetName' => 'Tools'
),
'portalData' => array
(
),
'recordId' => 829,
'modId' => 1
),
2 => array
(
'fieldData' => array
(
'groupAssetID' => 1005,
'groupAssetName' => 'Spare Parts'
),
'portalData' => array
(
),
'recordId' => 830,
'modId' => 1
)
)
),
'messages' => array
(
0 => array
(
'code' => 0,
'message' => 'OK'
)
)
);
foreach ($records['response']['data'] as $key => $value) {
echo $value['fieldData']['groupAssetID'] . ": " . $value['fieldData']['groupAssetName'] . "<br />\r\n" ;
}
Output:
1020: Standard Equipment
1001: Tools
1005: Spare Parts
Is this what you need?

Change key of multidimensional array

I have following array as response from db. I am trying to convert this database response into multidimensional array as per my requirement.
Array
(
[0] => Array
(
[0] => Array
(
[_id] => C10359
[AE] => Array
(
[0] => 89785
[1] => 89786
[2] => 89857
[3] => 89859
)
)
[1] => Array
(
[_id] => C10428
[AE] => Array
(
[0] => 50191
[1] => 50203
[2] => 50230
[3] => 50244
)
)
)
[1] => Array
(
[0] => Array
(
[_id] => C10350
[AE] => Array
(
[0] => 89785
[1] => 89786
[2] => 89857
[3] => 89859
)
)
[1] => Array
(
[_id] => C10430
[AE] => Array
(
[0] => 50191
[1] => 50203
[2] => 50230
[3] => 50244
)
)
)
)
Now I need to convert above array in following way.
Array
(
[0] => Array
(
[C10359] => Array
(
[0] => 89785
[1] => 89786
[2] => 89857
[3] => 89859
)
[C10428] => Array
(
[0] => 50191
[1] => 50203
[2] => 50230
[3] => 50244
)
)
[1] => Array
(
[C10350] => Array
(
[0] => 89785
[1] => 89786
[2] => 89857
[3] => 89859
)
[C10430] => Array
(
[0] => 50191
[1] => 50203
[2] => 50230
[3] => 50244
)
)
)
following is way i am trying
array_map(function($arr) {
return $arr[0] ;
},$panel_result);
But it is not working.
Kindly suggest how can I convert in required formate.
This should do the trick :
$arr = array(
array(
array(
'_id' => 'C10359',
'AE' => array
(
89785,
89786,
89857,
89859,
),
),
array(
'_id' => 'C10428',
'AE' => array
(
50191,
50203,
50230,
50244,
),
),
),
);
$output = array();
foreach ($arr as $levelK => $level) {
if(!isset($output[$levelK])){
$output[$levelK] = array();
}
foreach ($level as $subLevel) {
$id = $subLevel['_id'];
if (!isset($output[$levelK][$id])) {
$output[$levelK][$id] = array();
}
foreach ($subLevel['AE'] as $val) {
$output[$levelK][$id][] = $val;
}
}
}
Hope this helps.
Use array_column() and pass third param as the index key.
$reqArray = array();
foreach ($yourArray as $key => $innerArray) {
$reqArray[] = array_column($innerArray, 'AE', '_id');
}
OR
Use array map()
$reqArray = array_map(function($a){
return array_column($a, 'AE', '_id');
},$arr);

PHP Array re-arrange to Multi Dimensional

I have an array structure like this and wanted to Re-arrange it to the one below. Any suggestions for a faster/simple fix? I already did the addition of the dates. Thanks! :)
Input:
Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
[company_name] => Company_A
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
[company_name] => Company_A
)
[2] => Array
(
[user_id] => 25
[display_name] => Hulk
[company_name] => Company_B
)
[3] => Array
(
[user_id] => 50
[display_name] => Bob
[company_name] => Company_B
)
)
Output:
Array
(
[Company_A] => Array
(
[company_total_hours] => 20h 45m
[employees] => Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
)
)
)
[Company_B] => Array
(
[company_total_hours] => 7h 30m
[employees] => Array
(
[0] => Array
(
[user_id] => 25
[display_name] => Hulk
)
[1] => Array
(
[user_id] => 50
[display_name] => Bob
)
)
)
)
My Attempts:
<?php
$company_names = array();
foreach ($records as $k => $v) {
$company_names[] = $v->company_name;
}
$company_names = array_unique($company_names);
// hard coded testing
if (count($company_names) > 0) {
foreach($company_names as $k2 => $v2) {
$final_array[$v2]['company_total_hours'] = rand(1, 20);
$final_array[$v2]['employees'] = array(
array('user_id' => '255', 'display_name' => 'Mark'),
array('user_id' => '150', 'display_name' => 'Paul')
);
}
}
// on-going testing right now here....
I don't see where you derive your hours from so I left that out.
$i = 0;
foreach($vals as $keys => $arrays) {
if(!isset($new[$arrays['company_name']]))
$i = 0;
$new[$arrays['company_name']]['employees'][$i]['display_name'] = $arrays['display_name'];
$new[$arrays['company_name']]['employees'][$i]['user_id'] = $arrays['user_id'];
$i++;
}
Gives you:
Array
(
[Company_A] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Mark
[user_id] => 255
)
[1] => Array
(
[display_name] => Paul
[user_id] => 150
)
)
)
[Company_B] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Hulk
[user_id] => 25
)
[1] => Array
(
[display_name] => Bob
[user_id] => 50
)
)
)
)
foreach($arr as $v)
{
if(!$arr2[$v['company_name']]['employees'])
$arr2[$v['company_name']]['employees'] = array();
if(!$arr2[$v['company_name']]['company_total_hours'])
$arr2[$v['company_name']]['company_total_hours'] = '2h';//addional value
$arr2[$v['company_name']]['employees'][] = array('user_id'=>$v['user_id'],
'display_name'=>$v['display_name']
);
}
I have created a function which does the same thing as the answer given by #Rasclatt.
function groupByKeyValue($array, $oldKeyName, $newKeyName){
$newArray = array();
foreach($array as $key=>$value){
if(isset($newArray[$value[$oldKeyName]][$newKeyName])){
$newArray[$value[$oldKeyName]][$newKeyName][] = array('user_id'=> $value['user_id'], 'display_name' => $value['display_name']);
}else{
$newArray[$value[$oldKeyName]] = array($newKeyName => array(array('user_id'=> $value['user_id'], 'display_name' => $value['display_name'])));
}
}
return $newArray;
}
//usage
$newArray = groupByKeyValue($array, 'company_name', 'employees');
You can add a third parameter to send the keys for the array values which needs to be used in the new array for 'employees'. Please check this link for the working of the function http://goo.gl/I6Of5y

Find a value in nested associative array

I want to get the value of 'GUID' with the value of 'SamAccountName'. i.e. I only have the value pf 'SamAccountName' and I would like to get the value of 'GUID' for that part of the array.
Array
(
[0] => Array
(
[DistinguishedName] => CN=johnn#playgroundla,OU=playgroundla,OU=Hosting,DC=exch024,DC=domain,DC=local
[GUID] => 26d7c204-7db7-4601-8cd2-0dd0d3b37d97
[OriginatingServer] => dcprov024-CA-1.exch024.domain.local
[Name] => johnn#playgroundla
[HostingObjectType] => Array
(
[HostingObjectTypes] => Array
(
[0] => ActiveSync
[1] => MSExchange2007Mailbox
[2] => ActiveDirectoryUser
)
)
[HostingOwners] => Array
(
[HostingObjectOwners] => Array
(
[0] => MSExchange2007Mailboxes
[1] => ActiveDirectoryUsers
)
)
[Attributes] => Array
(
[Hidden] =>
[ReadOnly] =>
[SpecialAccess] =>
[Items] => Array
(
)
)
[DisplayName] => John Nolan
[SamAccountName] => johnn_playgroundla
[FullSamAccountName] => EXCH024\johnn_playgroundla
[UserPrincipalName] => johnn#playgroundla.com
[AccountExpires] =>
[Enabled] =>
[EnabledFeatures] => Array
(
[string] => Array
(
[0] => ActiveSync
[1] => MSExchangeMailboxes
[2] => ActiveDirectoryUsers
)
)
[LastLogonTimestamp] =>
)
[1] => Array
(
[DistinguishedName] => CN=csliney#playgroundla,OU=playgroundla,OU=Hosting,DC=exch024,DC=domain,DC=local
[GUID] => 71224be8-1b8b-46e7-97ef-2cd873bf9b7f
[OriginatingServer] => dcprov024-CA-1.exch024.domain.local
[Name] => csliney#playgroundla
[HostingObjectType] => Array
(
[HostingObjectTypes] => Array
(
[0] => ActiveSync
[1] => MSExchange2007Mailbox
[2] => ActiveDirectoryUser
)
)
[HostingOwners] => Array
(
[HostingObjectOwners] => Array
(
[0] => MSExchange2007Mailboxes
[1] => ActiveDirectoryUsers
)
)
[Attributes] => Array
(
[Hidden] =>
[ReadOnly] =>
[SpecialAccess] =>
[Items] => Array
(
)
)
[DisplayName] => Christopher Sliney
[SamAccountName] => csliney_playgroundla
[FullSamAccountName] => EXCH024\csliney_playgroundla
[UserPrincipalName] => csliney#playgroundla.com
[AccountExpires] =>
[Enabled] =>
[EnabledFeatures] => Array
(
[string] => Array
(
[0] => ActiveSync
[1] => MSExchangeMailboxes
[2] => ActiveDirectoryUsers
)
)
[LastLogonTimestamp] =>
)
[2] => Array
(
[DistinguishedName] => CN=lee#playgroundla,OU=playgroundla,OU=Hosting,DC=exch024,DC=domain,DC=local
[GUID] => b428b57f-4cd4-4243-a76a-f25f5ff3be97
[OriginatingServer] => dcprov024-CA-1.exch024.domain.local
[Name] => lee#playgroundla
[HostingObjectType] => Array
(
[HostingObjectTypes] => Array
(
[0] => MSExchange2007Mailbox
[1] => ActiveDirectoryUser
)
)
[HostingOwners] => Array
(
[HostingObjectOwners] => Array
(
[0] => MSExchange2007Mailboxes
[1] => ActiveDirectoryUsers
)
)
[Attributes] => Array
(
[Hidden] =>
[ReadOnly] =>
[SpecialAccess] =>
[Items] => Array
(
)
)
[DisplayName] => Lee Roderick
[SamAccountName] => lee_playgroundla
[FullSamAccountName] => EXCH024\lee_playgroundla
[UserPrincipalName] => lee#playgroundla.com
[AccountExpires] =>
[Enabled] =>
[EnabledFeatures] => Array
(
[string] => Array
(
[0] => MSExchangeMailboxes
[1] => ActiveDirectoryUsers
)
)
[LastLogonTimestamp] =>
)
[3] => Array
(
[DistinguishedName] => CN=theresa#playgroundla,OU=playgroundla,OU=Hosting,DC=exch024,DC=domain,DC=local
[GUID] => 4b2aee17-9e88-4de9-b95b-63a9877835a6
[OriginatingServer] => dcprov024-CA-1.exch024.domain.local
[Name] => theresa#playgroundla
[HostingObjectType] => Array
(
[HostingObjectTypes] => Array
(
[0] => ActiveSync
[1] => MSExchange2007Mailbox
[2] => ActiveDirectoryUser
)
)
[HostingOwners] => Array
(
[HostingObjectOwners] => Array
(
[0] => MSExchange2007Mailboxes
[1] => ActiveDirectoryUsers
)
)
[Attributes] => Array
(
[Hidden] =>
[ReadOnly] =>
[SpecialAccess] =>
[Items] => Array
(
)
)
[DisplayName] => Theresa Baker
[SamAccountName] => theresa_playgroundla
[FullSamAccountName] => EXCH024\theresa_playgroundla
[UserPrincipalName] => theresa#playgroundla.com
[AccountExpires] =>
[Enabled] =>
[EnabledFeatures] => Array
(
[string] => Array
(
[0] => ActiveSync
[1] => MSExchangeMailboxes
[2] => ActiveDirectoryUsers
)
)
[LastLogonTimestamp] =>
)
)
This was originally a stdClass object but I used json_decode(json_encode($obj), true) to convert to an associative array.
Sounds like you want to get the GUID portion for the value of 'SamAccountName'. Use a foreach loop:
function getGUID($san, $array) {
foreach($array as $a) {
if($a['SamAccountName'] == $san) {
return $a['GUID'];
}
}
return false;
}
$guid = getGUID("SamAccountNameHere", $yourArray);
You can use a simple loop to fetch it
$id = 0;
foreach($data as $item) {
if (isset($item['SamAccountName']) && 'accountName' == $item['SamAccountName']) {
$id = $item['GUID'];
break;
}
}
var_dump($id);
is this what you are looking for?
function findBySam($arrayList, $sam) {
foreach($arrayList as $array) {
if($array['SamAccountName'] == $sam) {
return $array;
}
}
return false;
}
Here is an example of a function that you could use. This assumes that there will be only one object with the SamAccountName that you supply in the array (it just uses the first one that it finds). It returns the GUID of the matching array and false if it cannot find an array with a matching SamAccountName.
function getGuidForSamAccountName($arr, $name) {
foreach ($arr as $elem) {
if ($elem['SamAccountName'] === $name) {
return $elem['GUID'];
}
}
return false; //No match found
}
You can use array_filter function of php:
http://php.net/manual/en/function.array-filter.php
example:
$GUID = "sample";
array_filter($array, "findElement");
function findElement($el) {
return $el["GUID"] == $_GLOBAL["GUID"];
}
Not a very elegant solution... but it should work.

PHP Associative array sort

I have an array like one below.
Currently it is sorted alphabetically by the OwnerNickName field.
Now i want to brig the array entry with OwnerNickName 'My House' as the first entry of the array and rest sorted alphabetically by OwnerNickName.
Any idea?
Array
(
[0318B69D-5DEB-11DF-9D7E-0026B9481364] => Array
(
[OwnerNickName] => andy
[Rooms] => Array
(
[0] => Array
(
[Label] => Living Room
[RoomKey] => FC795A73-695E-11DF-9D7E-0026B9481364
)
)
)
[286C29DE-A9BE-102D-9C16-00163EEDFCFC] => Array
(
[OwnerNickName] => anton
[Rooms] => Array
(
[0] => Array
(
[Label] => KidsRoom
[RoomKey] => E79D7991-64DC-11DF-9D7E-0026B9481364
)
[1] => Array
(
[Label] => Basement
[RoomKey] => CC12C0C4-68AA-11DF-9D7E-0026B9481364
)
[2] => Array
(
[Label] => Family Room
[RoomKey] => 67A280D4-64D9-11DF-9D7E-0026B9481364
)
)
)
[8BE18F84-AC22-102D-9C16-00163EEDFCFC] => Array
(
[OwnerNickName] => mike
[Rooms] => Array
(
[0] => Array
(
[Label] => Family Room
[RoomKey] => 1C6AFB39-6835-11DF-9D7E-0026B9481364
)
)
)
[29B455DE-A9BC-102D-9C16-00163EEDFCFC] => Array
(
[OwnerNickName] => My House
[Rooms] => Array
(
[0] => Array
(
[Label] => Basement
[RoomKey] => 61ECFAB2-6376-11DF-9D7E-0026B9481364
)
[1] => Array
(
[Label] => Rec Room
[RoomKey] => 52B8B781-6376-11DF-9D7E-0026B9481364
)
[2] => Array
(
[Label] => Deck
[RoomKey] => FFEB4102-64DE-11DF-9D7E-0026B9481364
)
[3] => Array
(
[Label] => My Room2
[RoomKey] => 112473E4-64DF-11DF-9D7E-0026B9481364
)
[4] => Array
(
[Label] => Bar Room
[RoomKey] => F82C47A8-64DE-11DF-9D7E-0026B9481364
)
)
)
)
You may want to implement your own sorting function, e.g.:
function cmp($a, $b)
{
if ($a['OwnerNickName'] == $b['OwnerNickName']) {
return 0;
}
if ($a['OwnerNickName'] == 'My House') {
return -1;
} else if ($b['OwnerNickName'] == 'My House') {
return 1;
}
return ($a['OwnerNickName'] < $b['OwnerNickName']) ? -1 : 1;
}
usort($array, 'cmp');
If you want to change your mind about which index to sort on or which value should be special, something like this might suit:
function specialSort(array &$array, $index, $specialvalue){
$callback = function($a,$b) use ($index, $specialvalue) { //closure
if ($a[$index] == $b[$index]) return 0;
if ($a[$index] == $specialvalue) return -1;
if ($b[$index] == $specialvalue) return 1;
return ($a[$index] < $b[$index]) ? -1 : 1;
} ;
uasort($array, $callback);
}
$arr=array(
'a'=>array('thing'=>'yay','who'=>'owee'),
'foo'=>array('thing'=>'boo','who'=>'wik'),
'd'=>array('thing'=>'kil','who'=>'ilo'),
'b'=>array('thing'=>'ser','who'=>'uyt'),
'zed'=>array('thing'=>'efv','who'=>'qet')
);
specialSort($arr,'who','ilo');
print_r($arr);
Gives the result:
Array
(
[d] => Array
(
[thing] => kil
[who] => ilo //special value
)
[a] => Array
(
[thing] => yay
[who] => owee
)
[zed] => Array
(
[thing] => efv
[who] => qet
)
[b] => Array
(
[thing] => ser
[who] => uyt
)
[foo] => Array
(
[thing] => boo
[who] => wik
)
)

Categories