I have multidimensional array as follows,
[0] => Array
(
[data] =>
[id] => 0000
[name] => Swirl
[categories] => Array
(
[0] => Array
(
[id] => 0001
[name] => Whirl
[products] => Array
(
[0] => Array
(
[id] => 0002
[filename] => 1.jpg
)
[1] => Array
(
[id] => 0003
[filename] => 2.jpg
)
)
)
)
)
I have used the following function to find keys.
function find_parent($array, $needle, $parent = null) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$pass = $parent;
if (is_string($key)) {
$pass = $key;
}
$found = find_parent($value, $needle, $pass);
if ($found !== false) {
return $found;
}
} else if ($key === $needle) {
return $parent;
}
}
return false;
}
$parentkey = find_parent($array, 'id');
Now i need to unset the products array and replace it with another array.
how to do this.please help.
Thanks,
sarnitha
You can use a recursive function over an array:
function replaceInArray(array &$arr, $needleKey, array $replacement) {
foreach ($arr as $k => $v) {
if ($k === $needleKey) {
$arr[$k] = $replacement;
} else {
if (is_array($v)) {
replaceInArray($arr[$k], $needleKey, $replacement);
}
}
}
}
replaceInArray($sourceArr, 'products', ['id' => '0004', 'filename' => 'new.jpg']);
function replaceInArrayWithKey(array &$arr, $needleKey, array $replacementArray, $replacementKey) {
foreach ($arr as $k => $v) {
if ($k === $needleKey) {
$arr[$replacementKey] = $replacementArray;
unset($arr[$k]);
} else {
if (is_array($v)) {
replaceInArrayWithKey($arr[$k], $needleKey, $replacementArray, $replacementKey);
}
}
}
}
replaceInArrayWithKey($sourceArray, 'products', ['id' => '0004', 'filename' => 'new.jpg'], 'products_new');
You can also try using a built-in recursive iterator - https://www.php.net/manual/en/class.recursivearrayiterator.php
Related
Can you help me refactor this block of code? I'm quite having a hard time to decide how can I refactor nested for each loop or not use foreach loop at all.
$matcherResults = [];
foreach ($resultItems as $reqId => $resultItem) {
if (empty($resultItem)) {
continue;
}
foreach ($resultItem as $reg => $data) {
if (empty($data)) {
continue;
}
foreach ($data as $regs => $regData) {
if (empty($regData)) {
continue;
}
$matcherResult = new MatcherResult(
$regData,
null,
$reg,
$reqId
);
array_push($matcherResults, $matcherResult);
}
}
}
I've tried doing this but unable to come up with the MatcherResult object.
foreach ($resultItems as $reqId => $resultItem) {
$resultItem = array_filter($resultItem, function($resultItem) {
if(!empty($resultItem)) {
return true;
}
});
}
foreach ($resultItem as $regs => $value) {
$matcherResults = array_filter($value, function($value) {
return !empty($value);
});
}
EDIT:
As requested.
Here is a sample of resultItems.
Array
(
[3] => Array
(
[test1] => Array
(
[0] => Array
(
[database] => test1
[active] => 1
[reg] => test1
[full_name] => fname1 lname1
[image_url] => image.png
[last_name] => lname1
[first_name] => fname1
)
)
)
)
Is it possible that one of the lower levels could be a null instead of an empty array? If empty is just checking for an empty array, you could do this:
$matcherResults = [];
foreach ($resultItems as $reqId => $resultItem) {
foreach ($resultItem as $reg => $data) {
foreach ($data as $regs => $regData) {
if (!empty($regData)) {
$matcherResult = new MatcherResult(
$regData,
null,
$reg,
$reqId
);
array_push($matcherResults, $matcherResult);
}
}
}
}
I need to remove empty items in a multidimensional array.
Is there a simple way I can remove the empty items easily?
I need to keep only 2010-06 and 2010-07.
Thank you very much!
Array
(
[2010-01] => Array
(
[2010-03] => Array
(
[0] =>
)
[2010-04] => Array
(
[0] =>
)
[2010-06] => Array
(
[0] => stdClass Object
(
[data_test] => value
[date] => 2010-05-01 12:00:00
)
)
[2010-07] => Array
(
[0] => stdClass Object
(
[data_test] => value
[date] => 2010-05-01 12:00:00
)
)
)
)
Try this Function. This will solve your issue.
function cleanArray($array)
{
if (is_array($array))
{
foreach ($array as $key => $sub_array)
{
$result = cleanArray($sub_array);
if ($result === false)
{
unset($array[$key]);
}
else
{
$array[$key] = $result;
}
}
}
if (empty($array))
{
return false;
}
return $array;
}
array_filter will not wrok with this array
so try this custom function
<?php
$array =array(
20 => array(
20 => array(
0=> ''
),
10 => array(
0=> 'hey'
)
)
);
function array_remove_empty($arr){
$narr = array();
while(list($key, $val) = each($arr)){
if (is_array($val)){
$val = array_remove_empty($val);
// does the result array contain anything?
if (count($val)!=0){
// yes :-)
$narr[$key] = $val;
}
}
else {
if (trim($val) != ""){
$narr[$key] = $val;
}
}
}
unset($arr);
return $narr;
}
print_r(array_remove_empty($array));
?>
found this answer here
I come up with this code:
function multiArrayFlip($array)
{
$arrayCount = count($array);
if ($arrayCount != count($array, COUNT_RECURSIVE))
{
foreach($array as $key => $value)
{
if (is_array($value))
{
$array[$key] = multiArrayFlip($value);
}
}
}
else
{
array_flip($array);
}
return $array;
}
but it doesnt work.
It returns unchanged array.
here is the array data sample:
Array
(
[0] => Array
(
[0] => Array
(
[zip] => 02135
[hispanic_percent] => 7.4
[white_percent] => 73.1
[black_percent] => 4.2
[native_american_percent] => 0
)
)
[1] => Array
(
[0] => Array
(
[zip] => 02135
[school_number] => 1
[school_name] => ANOTHER COURSE TO COLLEGE
[school_address] => 20 WARREN STREET BRIGHTON MA 02135
[contact_number] => 617-635-8865
[start_grade] => 9TH GRADE
[reduced_lunch_students_count] => 8
[reduced_lunch_students_percent] => 120
[free_or_reduced_lunch_students_count] => 53
[free_or_reduced_lunch_students_percent] => 0
)
)
)
You have to reassign the return value of the array_flip function to your $array variable in order to work.
You need to modify your function to work it correctly. Reassign the values after array_flip
function multiArrayFlip($array)
{
$arrayCount = count($array);
if ($arrayCount != count($array, COUNT_RECURSIVE))
{
foreach($array as $key => $value)
{
if (is_array($value))
{
$array[$key] = multiArrayFlip($value);
}
}
}
else
{
$array = array_flip($array);
}
return $array;
}
Hope this helps :)
My array is like:
Array
(
[0] => Array
(
[id] => 6
[name] => Name1
)
[1] => Array
(
[id] => 7
[name] => Name2
)
)
How can I check any perticular value of name exists in this multi-dimentional array?
function checkName($haystack, $needle) {
foreach($haystack as $hay) {
if($hay['name'] == $needle) {
return true;
}
}
return false;
}
Iterate.
function multi_in_array($name, $array) {
foreach ($array as $sub_array) {
if (in_array($name, $array)) {
return true;
}
}
return false;
}
perhaps you're looking for in_array function?
With that structure, your only option is essentially a linear search:
$found = null;
foreach ($arr as $idx => $elem) {
if ($elem['name'] == $searchName) {
$found = $idx;
}
}
if ($found !== null) {
echo "Found $searchName at $idx.";
}
This function will help you,
<?php
function multi_dim_array_search($array,$col,$val)
{
foreach($array as $elem)
if($elem[$col] == $val)
return true;
return false;
}
$array = array(
array('id' => 1,'name' => 'Name1'),
array('id' => 2,'name' => 'Name2')
);
//usage
var_dump(multi_dim_array_search($array,'name','Name1')); //true
var_dump(multi_dim_array_search($array,'name','Name2')); //true
var_dump(multi_dim_array_search($array,'name','Name3')); //false
?>
I'm trying to find a way to return the value of an array's parent key.
For example, from the array below I'd like to find out the parent's key where $array['id'] == "0002".
The parent key is obvious because it's defined here (it would be 'products'), but normally it'd be dynamic, hence the problem. The 'id' and value of 'id' is known though.
[0] => Array
(
[data] =>
[id] => 0000
[name] => Swirl
[categories] => Array
(
[0] => Array
(
[id] => 0001
[name] => Whirl
[products] => Array
(
[0] => Array
(
[id] => 0002
[filename] => 1.jpg
)
[1] => Array
(
[id] => 0003
[filename] => 2.jpg
)
)
)
)
)
A little crude recursion, but it should work:
function find_parent($array, $needle, $parent = null) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$pass = $parent;
if (is_string($key)) {
$pass = $key;
}
$found = find_parent($value, $needle, $pass);
if ($found !== false) {
return $found;
}
} else if ($key === 'id' && $value === $needle) {
return $parent;
}
}
return false;
}
$parentkey = find_parent($array, '0002');
Since you have a tree structure either of a BFS or DFS can do it. Since the structure is variable a recursive solution would work well. Simply return a sentinel when you find the value, then return the key in the caller.
function array_to_xml($array, $rootElement = null, $xml = null) {
$_xml = $xml;
if ($_xml === null) {
$_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>');
}
$has_int_key = 0;
foreach ($array as $k => $v) {
if (is_array($v)) {
if(is_int($k)){
$this->array_to_xml($v, $k, $_xml->addChild($rootElement));
}
else {
foreach($v as $key=>$value) {
if(is_int($key)) $has_int_key = 1;
}
if ($has_int_key) {
$this->array_to_xml($v, $k, $_xml);
} else {
$this->array_to_xml($v, $k, $_xml->addChild($k));
}
}
}
else {
$_xml->addChild($k, $v);
}
}
return $_xml->asXML();
}