Convert multi-dimensional array to flat array php - php

I have a problem in converting multi-dimensional array to flat array
I have an input array like this:
Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[aggregator] => all
[conditions] => Array
(
[0] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
)
)
[1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
[2] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => attribute_set_id
)
)
and I want the output is an array like this, the child array will be flattened as parent array level and it will be recognized by the index:
Array
(
[1--1] => Array
(
[type] => Magento\CatalogRule\Model\Rule\Condition\Combine
[aggregator] => all
)
[1--1--1] => Array
(
[type] => Magento\CatalogRule\Model\Rule\Condition\Product
[attribute] => category_ids
)
[1--2] => Array
(
[type] => Magento\CatalogRule\Model\Rule\Condition\Product
[attribute] => category_ids
)
[1--3] => Array
(
[type] => Magento\CatalogRule\Model\Rule\Condition\Product
[attribute] => attribute_set_id
)
)
the input array may contain many child layers and the output array must be index in that format.
I'm stucking to write this logic into code. Thank you!

You can use a recursive function like this:
function flatten($array, $parent_key = '1') {
$flattened_array = [];
foreach ($array as $key => $item) {
$tmp = $item;
unset($tmp['conditions']);
$child_key = $parent_key . '--' . strval($key + 1);
$flattened_array[$child_key] = $tmp;
if (isset($item['conditions'])) {
$flattened_array = array_merge($flattened_array, flatten($item['conditions'], $child_key));
}
}
return $flattened_array;
}
$input = [
0 => [
'type' => 'MagentoCatalogRuleModelRuleConditionCombine',
'aggregator' => 'all',
'conditions' => [
0 => [
'type' => 'MagentoCatalogRuleModelRuleConditionProduct',
'attribute' => 'category_ids'
]
]
],
1 => [
'type' => 'MagentoCatalogRuleModelRuleConditionProduct',
'attribute' => 'category_ids'
],
2 => [
'type' => 'MagentoCatalogRuleModelRuleConditionProduct',
'attribute' => 'attribute_set_id'
]
];
print_r(flatten($input));
Output:
Array
(
[1--1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionCombine
[aggregator] => all
)
[1--1--1] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
[1--2] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => category_ids
)
[1--3] => Array
(
[type] => MagentoCatalogRuleModelRuleConditionProduct
[attribute] => attribute_set_id
)
)

Related

PHP Sort multi-dimension array by keys

I have a multi dimension array like below:
Array
(
[1200] => Array
(
[B] => Array
(
[4] => Array
(
[Name] => 'Joe']
)
)
[A] => Array
(
[3] => Array
(
[Name] => 'Paul']
)
)
)
[1100] => Array
(
[F] => Array
(
[2] => Array
(
[Name] => 'Sam']
)
)
[D] => Array
(
[1] => Array
(
[Name] => 'Jane']
)
)
)
What I wish to achieve is having the 4 digit number 1100 and 1200 in order ascending, then I need the letters (B A) and (F D) also in order, and then the single digit number under them in order ascending too. I believe I'm looking at a multi dimension array but any help would be appreciated.
The below function might be what you're looking for. It recursively orders arrays by their key.
function ksort_r(&$array) {
foreach ($array as &$value) {
if (is_array($value)) {
ksort_r($value);
}
}
return ksort($array);
}
Example usage
function ksort_r(&$array) {
foreach ($array as &$value) {
if (is_array($value)) {
ksort_r($value);
}
}
return ksort($array);
}
$data = [
1200 => [
'B' => [
4 => [
'Name' => 'Joe'
]
],
'A' => [
3 => [
'Name' => 'Paul'
]
]
],
1100 => [
'F' => [
2 => [
'Name' => 'Sam'
]
],
'D' => [
1 => [
'Name' => 'Jane'
]
]
]
];
ksort_r($data);
print_r($data);
The above will output...
Array
(
[1100] => Array
(
[D] => Array
(
[1] => Array
(
[Name] => Jane
)
)
[F] => Array
(
[2] => Array
(
[Name] => Sam
)
)
)
[1200] => Array
(
[A] => Array
(
[3] => Array
(
[Name] => Paul
)
)
[B] => Array
(
[4] => Array
(
[Name] => Joe
)
)
)
)

change a key of a single element array

I have an array tree from a database, I want to change the key of a child element in this case the second array 'eric'=>array into integer '0'=>array as follow :
0 => Array
('text' => 'paris',
'nodes' => Array
('eric' => Array
( 'text' => 'eric',
'nodes' => Array
(0 => Array
(
'text' => 'so.png',
),
),
),
),
),
there is my code :
while($d = mysqli_fetch_assoc($result)) {
if(!isset($data[$d['country']])) {
$data[$d['country']] = array(
'text' => $d['country'],
'nodes' => array()
);
}
if(!isset($data[$d['country']]['nodes'][$d['name']])) {
$data[$d['country']]['nodes'][$d['name']] = array(
'text' => $d['name'],
'nodes' => array()
);
}
array_push($data[$d['country']]['nodes'][$d['name']]['nodes'], $d['n_doc']);
}
To change all of the child keys to numeric values, you can simply just use array_values()
Live Demo
for($i = 0; $i <= count($data) -1; $i++) { # This loops through each country
$data[$i]['nodes'] = array_map(function($node) { # This preserves the parent text value
return array_values($node); # [0] => Paris, [1] => array(...)
}, $data[$i]['nodes']);
}
Output
[ ... => [ text => Paris, nodes => [ 0 => Paris, 1 => [ ... ] ] ... ] ... ]
can you change your code for this input:
Array
(
[0] => Array
(
[text] => paris
[nodes] => Array
(
[jacque] => Array
(
[text] => jacque
[nodes] => Array
(
[0] => 32.png
)
)
[anis] => Array
(
[text] => anis
[nodes] => Array
(
[0] => 5384a97ee9d6b (2).pd
)
)
)
)
[1] => Array
(
[text] => london
[nodes] => Array
(
[dodo] => Array
(
[text] => dodo
[nodes] => Array
(
[0] => 148782.svg
[1] => 333.png
)
)
[sd] => Array
(
[text] => sd
[nodes] => Array
(
[0] => 1014-favicon.ico
)
)
)
)
)

Filter elements from multidimensional array that contain specific string

I have the following array
Array
(
[0] => Array
(
[text] => Array
(
[content] => I
[beginOffset] => 0
)
[partOfSpeech] => Array
(
[tag] => PRON
[aspect] => ASPECT_UNKNOWN
[case] => NOMINATIVE
[form] => FORM_UNKNOWN
[gender] => GENDER_UNKNOWN
[mood] => MOOD_UNKNOWN
[number] => SINGULAR
[person] => FIRST
[proper] => PROPER_UNKNOWN
[reciprocity] => RECIPROCITY_UNKNOWN
[tense] => TENSE_UNKNOWN
[voice] => VOICE_UNKNOWN
)
[dependencyEdge] => Array
(
[headTokenIndex] => 1
[label] => NSUBJ
)
[lemma] => I
)
...
I want to remove all elements that contain the string "_UNKNOWN" as they are not necessairy
how would I go about that?
Assuming all your 'UNKNOWN' are going to be in 'partOfSpeech', you can use this simple code to remove all the elements containing the string '_UNKNOWN':
$array = ['text' => ['content' => 'I', 'beginOffset' => 0], 'partOfSpeech' => ['tag' => 'PRON', 'aspect' => 'ASPECT_UNKNOWN', 'form' => 'FORM_UNKNOWN']]; // Example array
$array['partOfSpeech'] = array_filter($array['partOfSpeech'],
function($item) {
return strpos($item, '_UNKNOWN') === false;
});
print_r($array);
Output:
Array ( [text] => Array ( [content] => I [beginOffset] => 0 ) [partOfSpeech] => Array ( [tag] => PRON ) )

make nested array on the basis of specific array value in php

Array
(
[0] => Array
(
[user_id] => 40718
[name] => abc1
)
[1] => Array
(
[user_id] => 40718
[name] => abc2
)
[2] => Array
(
[user_id] => 40719
[name] => abc3
)
)
my array is like having user_id as you can see above i want to convert it into nested array on the basis of specific value from array as user_id like mention below
Array
(
[40718] => Array
(
[0]=>array(
[name] => abc1
)
[1]=>array(
[name] => abc2
)
)
[40719] => Array
(
[0] => (
[name] => abc3
)
)
)
Though I haven't tested it, check if it can help you to get your result :
<?php
$arrTest = [
[
'user_id' => 40718,
'name' => 'abc1'
],
[
'user_id' => 40718,
'name' => 'abc2'
],
[
'user_id' => 40719,
'name' => 'abc3'
]
];
$resultArr = [];
foreach ($arrTest as $val) {
$resultArr[$val['user_id']][]['name'] = $val['name'];
}
echo '<pre>'; print_r($resultArr); exit;
?>

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.

Categories