How to Work with Dynamic Multidimensional Array in PHP? - php

I have dynamic multidimensional array like this :
Array
(
[0] => index.php
[src] => Array
(
[src2] => Array
(
[src3] => Array
(
[0] => test_src3.php
)
[0] => Array
(
[0] => test_src2.php
)
)
[0] => test_src.php
)
[src_test] => Array
(
[New Folder] => Array
(
)
[src_test2] => Array
(
[New Folder] => Array
(
)
[src_test3] => Array
(
)
)
)
[1] => test.php
)
The number of dimensions might be change based on sub directories that found in a folder path inputted by user (this program is used by a person in their local).
How could i fetch those array elements so that the result would be like this :
array(
[0] => src/src2/src3
[1] => src_test/New Folder
[2] => src_test/src_test2/New Folder/
[3] => src_test/src_test2/src_test3
)
By the way i have a function to achieve this :
function getKeyPaths(array $tree, $glue = '/'){
$paths = array();
foreach ($tree as $key => &$mixed) {
if (is_array($mixed)) {
$results = getKeyPaths($mixed, $glue);
foreach ($results as $k => &$v) {
$paths[$key . $glue . $k] = $v;
}
unset($results);
} else {
$paths[$key] = $mixed;
}
}
return $paths;
}
the above function does not result like what i expected:
Array
(
[0] => index.php
[src/src2/src3/0] => test_src3.php
[src/src2/0/0] => test_src2.php
[src/0] => test_src.php
)
How do i achieve this ?

One approach :
function getKeyPaths(array $tree, $glue = '/', $return_array = true){
$paths = "";
foreach ($tree as $key => &$mixed) {
$path = $key . $glue;
if (is_array($mixed) && !is_int($key) ) {
$paths .= $path . getKeyPaths( $mixed, $glue, false);
if ($return_array) {
$paths .= "|";
}
}
}
if ($return_array) {
return explode("|", trim($paths, "|"));
}
return $paths;
}

Related

PHP Group keys of associative array by values

function groupByOwners(array $files) : array { return []; }
$files = array("Input.txt" => "Randy","Code.py" => "Stan","Output.txt" =>"Randy");
Print_r(groupByOwners($files);
My expected output is:
[Randy => [Input.txt, Output.txt] , Stan => [Code.py]]
You just need to iterate over your array, pushing each filename to a new array indexed by the names:
function groupByOwners(array $files) : array {
$output = array();
foreach ($files as $file => $name) {
$output[$name][] = $file;
}
return $output;
}
$files = array("Input.txt" => "Randy","Code.py" => "Stan","Output.txt" =>"Randy");
print_r(groupByOwners($files));
Output:
Array
(
[Randy] => Array
(
[0] => Input.txt
[1] => Output.txt
)
[Stan] => Array
(
[0] => Code.py
)
)
Demo on 3v4l.org

How to parse arrays with different levels PHP

In a foreach loop i would like to compare [name] value beetween different arrays but they have not the same levels.
Array(
[array1] => Array
(
[0] => WP_Term Object
(
[name] => Plafond
)
)
[array2] => WP_Term Object
(
[name] => Chaudière
)
[array3] => Array
(
[0] => WP_Term Object
(
[name] => Pla
)
[1] => WP_Term Object
(
[name] => Toc
)
)
)
I don't know how could i get the [name] in the same loop whereas levels are different.
I have tried to make :
foreach( $fields as $name => $value )
{
echo $value->name; }
Should i add another loop in the first loop ?
thanks
So your data looks like this:
$json = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$array = json_decode($json);
If you don't know how deep it will go, a simple recursive function should work. Perhaps something like this:
function get_name($o, &$output) {
if (is_array($o)) {
foreach($o as $v) {
get_name($v, $output);
}
} elseif (property_exists($o, "name")) {
$output[] = $o->name;
}
}
$output = [];
foreach ($array as $v) {
get_name($v, $output);
}
If you data is going to look like the sample you provided (i.e. it will always be first or second level) then you don't need to worry about recursion.
$output = [];
foreach ($array as $k=>$v) {
if (is_array($v)) {
foreach ($v as $k2=>$v2) {
$output[] = $v2->name;
}
} else {
$output[] = $v->name;
}
}
Either way, your output values are all in the $output array:
print_r($output);
Output:
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use array_map, array_key_exists to retrive the name index from the array
$jsonFormat = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$jsonArray = json_decode($jsonFormat,true);
$res = [];
array_map(function($v) use (&$res){
if(array_key_exists('name', $v)){
$res[] = $v['name'];
}else{
foreach($v as $_key => $_value){
$res[] = $_value['name'];
}
}
}, $jsonArray);
echo '<pre>';
print_r($res);
Result:-
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use $res to compare the names.

Remove items from multidimensional array in PHP

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

How to get the value from serialized array by using preg_match in php

I need to get the value from the serialized array by matching the index value.My unserialized array value is like
Array ( [info1] => test service [price_total1] => 10
[info2] => test servicing [price_total2] => 5 )
I need to display array like
Array ( [service_1] => Array ([info]=>test service [price_total] => 10 )
[service_2] => Array ([info]=>test servicing [price_total] => 5 ))
buy i get the result like the below one
Array ( [service_1] => Array ( [price_total] => 10 )
[service_2] => Array ( [price_total] => 5 ) )
my coding is
public function getServices($serviceinfo) {
$n = 1;
$m = 1;
$matches = array();
$services = array();
print_r($serviceinfo);
if ($serviceinfo) {
foreach ($serviceinfo as $key => $value) {
if (preg_match('/info(\d+)$/', $key, $matches)) {
print_r($match);
$artkey = 'service_' . $n;
$services[$artkey] = array();
$services[$artkey]['info'] = $serviceinfo['info' . $matches[1]];
$n++;
}
if ($value > 0 && preg_match('/price_total(\d+)$/', $key, $matches)) {
print_r($matches);
$artkey = 'service_' . $m;
$services[$artkey] = array();
$services[$artkey]['price_total'] = $serviceinfo['price_total' . $matches[1]];
$m++;
}
}
}
if (empty($services)) {
$services['service_1'] = array();
$services['service_1']['info'] = '';
$services['service_1']['price_total'] = '';
return $services;
}
return $services;
}
I try to print the matches it will give the result as
Array ( [0] => info1 [1] => 1 ) Array ( [0] => price_total1 [1] => 1 )
Array ( [0] => info2 [1] => 2 ) Array ( [0] => price_total2 [1] => 2 )
Thanks in advance.
try this. shorted version and don't use preg_match
function getServices($serviceinfo) {
$services = array();
if (is_array($serviceinfo) && !empty($serviceinfo)) {
foreach ($serviceinfo as $key => $value) {
if(strpos($key, 'info') === 0){
$services['service_'.substr($key, 4)]['info']=$value;
}elseif (strpos($key, 'price_total') === 0){
$services['service_'.substr($key, 11)]['price_total']=$value;
}
}
}
return $services;
}
$data = array('info1'=>'test service','price_total1'=>10,'info2'=>'test servicing','price_total2'=>5);
$service = getServices($data);
print_r($service);

How do I invert a multi-dimensional array?

I have an array with n elements in it, with each element containing n child elements, each containing...
Array
(
[tea] => Array
(
[drink] => Array
(
[food] =>
)
)
[biscuits] => Array
(
[snack] => Array
(
[food] =>
)
)
...
)
What I want to do is have the inner most element on the outside, and the outer most elements on the inside:
Array
(
[food] => Array
(
[drink] => Array
(
[tea] =>
)
[snack] => Array
)
[biscuits] =>
(
)
...
)
And the solution needs to be able to deal with n children arrays. I am aware of How do I invert a multidimensional array in PHP but the solutions there did not solve this problem.
I'm pretty sure this could be condensed further, but it does the job:
function flatten(array $array) {
$key = array(key($array));
$val = current($array);
if (is_array($val)) {
$key = array_merge(flatten($val), $key);
}
return $key;
}
function build(array $path, array $result) {
$key = array_shift($path);
if (!isset($result[$key])) {
$result[$key] = $path ? array() : null;
}
if ($path) {
$result[$key] = build($path, $result[$key]);
}
return $result;
}
$result = array();
foreach ($array as $key => $value) {
$result = build(flatten(array($key => $value)), $result);
}
Demo: http://codepad.org/rnZPdWGG

Categories