I have a problem with my recursional function. May be you can help me.
My function below:
function showTree($items, $level = 0) {
$arr = [];
foreach ($items as $item) {
$arr[] = str_repeat(":", $level * 2) . $item['name'] . "<br />";
if (!empty($item['children'][0])) {
$level++;
$arr[] = $this->showTree($item['children'], $level);
}
}
return $arr;
}
And this generate the output:
Array
(
[0] => Category1
[1] => Array
(
[0] => ::SubCategory2
[1] => ::SubCategory1
[2] => Array
(
[0] => ::::SubSubCategory
)
)
)
But I need a little bit other data as my output:
Array
(
[0] => Category1
[1] => ::SubCategory2
[2] => ::SubCategory1
[3] => ::::SubSubCategory
)
Where is my mistake? Thanks!
P>S:
Input:
Array
(
[0] => Array
(
[id] => 1
[name] => Category1
[parent] => 0
[children] => Array
(
[0] => Array
(
[id] => 4
[name] => SubCategory2
[parent] => 1
[children] => Array
(
)
)
[1] => Array
(
[id] => 2
[name] => SubCategory1
[parent] => 1
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => SubSubCategory
[parent] => 2
[children] => Array
(
)
)
)
)
)
)
)
Change this line:
$arr[] = $this->showTree($item['children'], $level);
to:
$arr = array_merge($arr, $this->showTree($item['children'], $level));
I.e. don't add the array returned while walking the children as a new value into the current array but append the values from it to the current array.
Try this:
function showTree($items, $level = 0, &$arr = array()) {
foreach ($items as $item) {
$arr[] = str_repeat(":", $level * 2) . $item['name'] . "<br />";
if (!empty($item['children'][0])) {
$level++;
$this->showTree($item['children'], $level, $arr);
}
}
return $arr;
}
Related
I have a Multidimensional array, I need to find if array have same value of 'brand' attribute then return its id.
I tried via some array functions but it didn't work.
What I Tried:
1)
$backwards = array_reverse($attribute);
echo '<pre>';
$last_item = NULL;
$i = 0;
foreach ($backwards as $current_item) {
if ($last_item === $current_item[$i]['value']) {
echo '<pre>'; print_r($current_item[$i]['value']);
}
$last_item = $current_item[$i]['value'];
echo '<pre>'; print_r($last_item);
$i++;
}
2)
$j = 1;
$i = 0;
foreach ($attributeValues as $attributeData) {
foreach ($attribute as $value) {
if($value[$i]['value'] == $value[$j]['value']) {
echo '<pre>'; print_r($value); die();
}
$j++;
}
}
All my solution's not worked, please help.
[0] => Array
(
[0] => Array
(
[name] => brand
[value] => 54
[id] => 5251
[price] => 15000.0000
)
[1] => Array
(
[name] => model
[value] => 1200
[id] => 5251
[price] => 15000.0000
)
)
[1] => Array
(
[0] => Array
(
[name] => brand
[value] => 54
[id] => 5250
[price] => 15000.0000
)
[1] => Array
(
[name] => model
[value] => 1200
[id] => 5250
[price] => 12000.0000
)
)
[2] => Array
(
[0] => Array
(
[name] => brand
[value] => 89
[id] => 518
[price] => 100.0000
)
[1] => Array
(
[name] => model
[value] => 12
[id] => 518
[price] => 100
)
)
If [name]=>brand and [name]=>model value's of first array is same as second array's value then return [id].
You need two for loop.
$result =[];
foreach ($arr as $key => $value) {
foreach($value as $v){
$result[$v['name']][] = $v['id'];
}
}
$result = array_map("array_unique", $result); // to make it unique
print_r($result);
// if you want to check ids for brand
//print_r($result['brand']);
Output:
Array
(
[brand] => Array
(
[0] => 5251
[1] => 5250
[3] => 518
)
[model] => Array
(
[0] => 5251
[1] => 518
)
)
Demo.
EDIT
Then you can group it by name and value of it
$result =[];
foreach ($arr as $key => $value) {
foreach($value as $v){
$result[$v['name']."|".$v['value']][] = $v['id'];
}
}
$result = array_map("array_unique", $result);
print_r($result);die;
Demo.
you can use foreach and iterate through the array
$res = [];
foreach($arr as $k => $v){
if($v[0]['name'] == $v[1]['name'])
$res[$v[0]['name']] = $v[0]['id'];
}
If you want to match the index value try this
foreach($arr as $k => $v){
if($v[0]['value'] == $v[1]['value'])
$res[] = $v[0]['id'];
}
Working example
I have two arrays with different structures. Array 1 and Array 2 that I will name from MyList and MyFiles. I would get to return only MyList values that do not have in MyFiles. But the two arrays have different structures and I'm having trouble trying to compare
MyList
Array
(
[info] => Array
(
[0] => Array
(
[player] => Messi
[week] => Array
(
[id] => 252
[videos] => Array
(
[0] => Array
(
[id] => 2929850
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929848
[link] => best.mp4
)
[2] => Array
(
[id] => 2929847
[link] => dribbling.mp4
)
)
)
)
[1] => Array
(
[player] => CR7
[week] => Array
(
[id] => 251
[videos] => Array
(
[0] => Array
(
[id] => 2929796
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929795
[link] => best.mp4
)
)
)
)
[2] => Array
(
[player] => Neymar
[week] => Array
(
[id] => 253
[videos] => Array
(
[0] => Array
(
[id] => 2929794
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929793
[link] => best.mp4
)
)
)
)
)
)
MyFiles Array
Array
(
[252] => Array
(
[0] => Array
(
[id] => 2929850
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929848
[link] => best.mp4
)
)
[251] => Array
(
[0] => Array
(
[id] => 2929796
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929795
[link] => best.mp4
)
)
)
the comparison must be made by id of the week and id of the video
I tried this but it did not work out:
$new = array();
foreach ($list['info'] as $source) {
foreach ($source["week"]['videos'] as $keys => $videos) {
foreach ($file as $key => $upload) {
if ($source["week"]["id"] == $key ) {
for($i=0; $i<count($source["week"]["videos"]); $i++){
if($videos["id"] == $upload[$i]["id"]){
unset($videos);
}else{
$new[] = $videos;
}
}
} else {
$new[] = $videos;
}
}
}
}
The expected return would be something like this.
Array
(
[info] => Array
(
[0] => Array
(
[player] => Messi
[week] => Array
(
[id] => 252
[videos] => Array
(
[2] => Array
(
[id] => 2929847
[link] => dribbling.mp4
)
)
)
)
[2] => Array
(
[player] => Neymar
[week] => Array
(
[id] => 253
[videos] => Array
(
[0] => Array
(
[id] => 2929794
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929793
[link] => best.mp4
)
)
)
)
)
)
I have hidden the array in a usable format for my sake in the future should this answer be incorrect and need changing.
$desired = array();
$desired['info'][0]['player'] = 'Messi';
$desired['info'][0]['week']['id'] = 252;
$desired['info'][0]['week']['videos'][2]['id'] = 2929847;
$desired['info'][0]['week']['videos'][2]['link'] = 'dribbling.mp4';
$desired['info'][2]['player'] = 'Neymar';
$desired['info'][2]['week']['id'] = 253;
$desired['info'][2]['week']['videos'][0]['id'] = 2929794;
$desired['info'][2]['week']['videos'][0]['link'] = 'goals.mp4';
$desired['info'][2]['week']['videos'][1]['id'] = 2929793;
$desired['info'][2]['week']['videos'][1]['link'] = 'best.mp4';
$list = array();
$list["info"][0]["player"] = "Messi";
$list["info"][0]["week"]["id"] = "252";
$list["info"][0]["week"]["videos"][0]["id"] = 2929850;
$list["info"][0]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][0]["week"]["videos"][1]["id"] = 2929848;
$list["info"][0]["week"]["videos"][1]["link"] = "best.mp4";
$list["info"][0]["week"]["videos"][2]["id"] = 2929847;
$list["info"][0]["week"]["videos"][2]["link"] = "dribbling.mp4";
$list["info"][1]["player"] = "CR7";
$list["info"][1]["week"]["id"] = "251";
$list["info"][1]["week"]["videos"][0]["id"] = 2929796;
$list["info"][1]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][1]["week"]["videos"][1]["id"] = 2929795;
$list["info"][1]["week"]["videos"][1]["link"] = "best.mp4";
$list["info"][2]["player"] = "Neymar";
$list["info"][2]["week"]["id"] = "253";
$list["info"][2]["week"]["videos"][0]["id"] = 2929794;
$list["info"][2]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][2]["week"]["videos"][1]["id"] = 2929793;
$list["info"][2]["week"]["videos"][1]["link"] = "best.mp4";
$file = array();
$file[252][0]['id'] = 2929850;
$file[252][0]['link'] = 'goals.mp4';
$file[252][1]['id'] = 2929848;
$file[252][1]['link'] = 'best.mp4';
$file[251][0]['id'] = 2929796;
$file[251][0]['link'] = 'goals.mp4';
$file[251][1]['id'] = 2929795;
$file[251][1]['link'] = 'best.mp4';
Edit
function array_diff_assoc_recursive($array1, $array2) {
$difference=array();
foreach ($array1 as $key => $value) {
if (is_array($value)) {
if( !isset($array2[$key]) || !is_array($array2[$key])) {
$difference[$key] = $value;
} else {
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if (!empty($new_diff))
$difference[$key] = $new_diff;
}
} else if (!array_key_exists($key,$array2) || $array2[$key] !== $value) {
$difference[$key] = $value;
}
}
return $difference;
}
$new = array('info' => array());
foreach ($list['info'] as $key => $item) {
$a = $item['week']['videos'];
//$b = $file[$item['week']['id']] ?? []; // This is PHP7+
$b = isset($file[$item['week']['id']]) ? $file[$item['week']['id']] : [];
$c = array_diff_assoc_recursive($a, $b);
if (!empty($c)) {
$new['info'][$key] = $item;
$new['info'][$key]['week']['videos'] = $c;
}
}
You will need a function that will check the difference between the videos arrays.
What I do is simply iterate over the list array and then check the difference between that item and the file array. The difference is then stored in $c.
If there is a difference then if statement is fired which will store that player in the $new array and then replace the videos array with the difference array.
This is similar to what you were doing when you were unsetting variables.
How can I create a function to display an array as a tree. For example I want to obtain a decision tree which I want to walk until I get to the leafs based on the branch's values. I create the tree like bellow:
$tree= new DS_Tree();
$node=array('name' => 'start');
$tree->insert_node($node);
$tree->goto_root();
$mytree = new id3();
$mytree->init($data_array_AttrList,$data_array_values,$data_class,$data_array_instances,$tree);
$mytree->run();
echo '<pre class="brush: php">';
print_r($mytree->tree->draw_tree());
echo '</pre>';
The function draw_tree() is:
public function draw_tree() {
return $this->nodes;
}
The function that creates my tree is:
private function make_tree($attr) {
foreach($this->Values[$attr] as $v) {
$subset = $this->get_subset($attr, $v);
if($the_class = $this->has_same_class($subset)) {
$node =array(
'name' => $attr,
'arc' => $v
);
$this->tree->insert_node($node);
$this->Instance = array_diff_key($this->Instance, $subset);
} else {
$node =array(
'name' => $this->Classa,
'arc' => $v
);
$unresolved = $this->tree->insert_node($node);
}
}
if (isset($unresolved)) {
$this->tree->goto_index($unresolved);
}
}
}
The result is:
Array
(
[0] => Array
(
[name] => Time
[parent] =>
[children] => Array
(
[0] => 1
)
)
[1] => Array
(
[name] => Focus
[arc] => Array
(
[0] => 2 day/week
[1] => 3 day/week
[2] => 4 day/week
[3] => 5 day/week
[4] => 6 day/week
)
[parent] => 0
[children] => Array
(
[0] => 2
)
)
[2] => Array
(
[name] => Dificulty
[arc] => Array
(
[0] => Weght loss
[1] => Mantain weight
[2] => Gain Mass
)
[parent] => 1
[children] => Array
(
[0] => 3
)
)
[3] => Array
(
[name] => Sex
[arc] => Array
(
[0] => Beginner
[1] => Intermediar
[2] => Advance
)
[parent] => 2
[children] => Array
(
[0] => 4
)
)
[4] => Array
(
[name] => Array
(
[Exercise] => Array
(
[0] => Array
(
[0] => Ex1
[1] => Ex2
[2] => Ex3
[3] => Ex4
[4] => Ex5
)
)
)
[arc] => Array
(
[0] => F
[1] => M
)
[parent] => 3
)
)
Just to display an array as a tree:
echo "<pre>";
var_dump($array);
echo "</pre>";
Here is a way to iterate through this data structure and look for a certain value:
function recurseFind($tree, $find, $path = "") {
if (!is_array($tree)) {
// it is a leaf:
if ($tree === $find) {
return $path; // return path where we found it
}
return false;
}
foreach($tree as $key => $value) {
$result = recurseFind($value, $find, $path . (is_numeric($key) ? "[$key]" : "['$key']"));
if ($result !== false) return $result;
}
return false;
}
For the sample input you provided, if you would call it like this:
echo recurseFind($tree, "Mantain weight", '$tree');
Outputs the "location" of that value (first match only) in a format that can be evaluated in PHP:
$tree[2]['arc'][1]
How to arrange this array by last inner index ( 0, 1, 2 ) and get the value of the last inner index as the value of each second index:
Array
(
[text] => Array
(
[grid] => Array
(
[0] => 3
[1] => 4
[2] => 5
)
[image] => Array
(
[0] =>
[1] =>
[2] =>
)
[align] => Array
(
[0] => left
[1] => right
[2] => left
)
[title] => Array
(
[0] =>
[1] =>
[2] =>
)
[content] => Array
(
[0] =>
[1] =>
[2] =>
)
)
)
And have the results as below:
Array
(
[text] => Array
(
[0] => Array
(
[grid] => 3
[image] =>
[align] => left
[title] =>
[content] =>
)
[1] => Array
(
[grid] => 4
[image] =>
[align] => right
[title] =>
[content] =>
)
[2] => Array
(
[grid] => 5
[image] =>
[align] => left
[title] =>
[content] =>
)
)
)
This will do the work
function restructure($arr){
$newArr = array();
foreach($arr as $k => $v){
foreach($v as $k1 => $v1){
foreach($v1 as $k2 => $v2){
$newArr[$k][$k2][$k1] = $v2;
}
}
}
return $newArr;
}
As SiGanteng suggested, i dont see other ways than a for/foreach loop:
function buildArray($source, $key = false)
{
// Build the new array
$new_array = array();
// Define groups
$groups = $key === false ? array_keys($source) : array($key);
foreach($groups AS $group)
{
// Get the keys
$keys = array_keys($array[$group]);
// Count the values
$num_entries = count($array[$group][$keys[0]]);
for($i = 0; $i < $num_entries; $i++)
{
foreach($keys AS $key)
{
$new_array[$group][$i][$key] = $array[$group][$key][$i];
}
}
}
return $new_array;
}
This allow you to define the key you need to build; If not specified, the function build the array for every key.
This should work.
function formatit($arr) {
$new = array();
foreach($arr as $k=>$v) {
foreach($v as $k1=>$v1) {
$new[$k1][$k] = $v1;
}
}
return $new;
}
Tested. Call it as
$arr['text'] = formatit($arr['text']);
http://ideone.com/rPzuR
I have tried to make a function that iterates through the following array to flatten it and add parent id to children, where applicable. I just can't make it work, so I hope that anyone here has an idea of what to do:
Here's the starting point:
Array
(
[0] => Array (
[id] => 1
[children] => array (
[id] => 2
[children] => Array (
[0] => Array (
[id] => 3
)
)
)
)
The expected result :
Array (
[0] => array (
[id] => 1
)
[1] => array (
[id] => 2
)
[2] => array (
[id] => 3,
[parent] => 2
)
)
Hope that anyone can point me in the right direction. Thanks a lot!
Solution (Thanks to Oli!):
$output = array();
function dejigg($in) {
global $output;
if (!isset($in['children'])) {
$in['children'] = array();
}
$kids = $in['children'] or array();
unset($in['children']);
if (!isset($in['parent'])) {
$in['parent'] = 0; // Not neccessary but makes the top node's parent 0.
}
$output[] = $in;
foreach ($kids as $child) {
$child['parent'] = $in['id'];
dejigg($child); // recurse
}
return $output;
}
foreach ($array as $parent) {
$output[] = dejigg($parent);
}
$array = $output;
print("<pre>".print_r($array,true)."</pre>");
I've tested it this time. This does work!
$input = array( array('id' => 1, 'children'=>array( array('id'=>2, 'children'=>array( array('id'=>3) ) ) ) ) );
$output = [];
function dejigg($in) {
global $output;
$kids = $in['children'] or array();
unset($in['children']);
$output[] = $in;
foreach ($kids as $child) {
$child['parent'] = $in['id'];
dejigg($child); // recurse
}
}
foreach ($input as $parent)
dejigg($parent);
print_r($output);
And it returns:
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
[parent] => 1
)
[2] => Array
(
[id] => 3
[parent] => 2
)
)