Converting a string with comma separated value in a tree in PHP - php

I have a csv file that contains a field with a category tree in a comma separated format like this:
MotherCategory, ChildCategory1, ChildCategory2, ecc.
Some records contains only a category, other ones two, other ones three or more.
I would like to be able to store in my db all the unique categories and organise every record with a parentid scheme where the parentid value is the id of the category one level up.
At the end I should have something like:
id: 1, catname: MotherCategory, parentid: NULL
id: 2, catname: ChildCategory1, parentid: 1
id: 3, catname: ChildCategory2, parentid: 2
I've already filtered the data removing duplicates with array_unique(), next using explode() I am able to separate the values and I was counting the values and separating the groups basing on the length of the resultant arrays to build a tree, but I think that at the moment I am missing something to get my final result.
I've the following code. Can someone please give me a hint to solve the problem?
$cats = array_of_comma_separated_values;
foreach ($cats as $cat) {
$catarray[] = explode(",",$cat);
}
//first level
$level1 = array_filter ($catarray, function($item) {
if (count($item) == 1) { return true; } return false;
});
//second level
$level2 = array_filter ($catarray, function($item) {
if (count($item) == 2) { return true; } return false;
});
$level3 = array_filter ($catarray, function($item) {
if (count($item) == 3) { return true; } return false;
});
$level4 = array_filter ($catarray, function($item) {
if (count($item) == 4) { return true; } return false;
});
$level5 = array_filter ($catarray, function($item) {
if (count($item) == 5) { return true; } return false;
});
$level6 = array_filter ($catarray, function($item) {
if (count($item) == 6) { return true; } return false;
});
$level7 = array_filter ($catarray, function($item) {
if (count($item) == 7) { return true; } return false;
});
This gives me several arrays that i've to iterate to achieve what i'm looking for.
Now thanks to the suggestion from Kovlar I'm working on something based on array_pop() and array_replace_recurive().
I've edited the post because maybe I was not so clear.

I suggest the use of array_replace_recursive() to simplify the tree-merging :)
// $tree will contain the tree at the end of the script
$tree = [];
// we treat each row of the csv one by one
foreach($csv_rows as $row) {
// first, we split the string into an array
$root_to_leaf = explode(',', $row['root_to_leaf']);
// this is the "leaf" we want to append to the tree
$leaf = [array_pop($root_to_leaf) => $row['value']];
// we rebuild the path from the leaf to the root
while(!empty($root_to_leaf)) {
// add the next branching toward the root
$leaf = [array_pop($root_to_leaf) => $leaf];
}
// we append the leaf to the tree
$tree = array_replace_recursive($tree, $leaf);
}

Related

PHP: How to get last array element in one array

i am trying to create function to check if array element is the last array element in one array. Original array looks like:
array(1001,
1002,
array('exam'=>true, 'index'=>10),
1003,
1004,
1005,
array('exam'=>true, 'index'=>20),
1006,
1007,
array('exam'=>true, 'index'=>30),
1008,
1009
)
I this case to prove if "array('exam'=>true, 'index'=>30)" is the last.
I have index position of that element, but I do not know how to check if that is the last array element.
function is_last_exam_in_survey($array, $exam_position) {
foreach($array as $element) {
if(!is_numeric($element) {
// check if that is the last array element in array
//return true;
} else {
// return false;
}
}
}
I would be grateful for any advice:)
function get_last_exam_in_survey($array) {
$last = null;
foreach($array as $element) {
if(is_array($element) && !empty($element['exam'])) {
$last = $element;
}
}
return $last;
}
function is_last_exam_in_survey($array, $exam_position) {
$last_exam = get_last_exam_in_survey($array);
return !empty($last_exam) && ($last_exam['index']==$exam_position);
}
I think this would be the quickest solution:
function is_last_exam_in_survey($array, $exam_position) {
$last_index = array_key_last( $array );
if( $exam_position == $last_index ){
return true;
}else{
return false;
}
}
You can still change the conditional statement if you are trying to compare values from the last element, for example:
if( isset($last_index['index']) && $exam_position == $last_index['index'] ){
Also, if you want to get the latest array value instead of key, you could use this:
$last_index = end( $array );
I would reverse the array, and look for the first element. Something like:
function is_last_exam_in_survey($array, $exam_position) {
foreach(array_reverse($array) as $element) {
if(!is_numeric($element) {
return $element['index'] === $exam_position;
}
}
return false;
}
Seems like the most efficient and simplest solution to me.
this solution avoid loop. at first we find out the last index of array.Then we use is_array() function for check the last element is array or not.
function get_last_exam_in_survey(array $arr)
{
$lastOfset = count($arr) - 1;
if(is_array($arr[$lastOfset])){
return true;
}else{
return false;
}
}
I think you can use array_column function to do that
function is_last_exam_in_survey($array,$exam_position){
$ac = array_column($array, 'index'); // return array(10,20,30)
$la = $ac[count($ac) - 1]; // 30
foreach ($array as $element) {
if (!is_numeric($element)) {
// check if $element['index'] === 30
if($element['index'] === $la){
return true;
}
}
}
}
How about using array_slice to extract the values in the array that are after the position you are looking at, then array_filter to remove any values that are not arrays. If there are any values left, then the entry you are looking at is not the last array entry in the array.
This may not be very efficient if you are calling it a lot of times with a large array. It may be better to rethink the way the data is stored or loaded into the array.
function is_last_exam_in_survey($array, $exam_position)
{
return isset($array[$exam_position])
&& is_array($array[$exam_position])
&& !array_filter(array_slice($array, $exam_position + 1), 'is_array');
}

Custom order for php array based on indexes

I have PHP array that looks like
$my_arr['cats'] = array('Shadow', 'Tiger', 'Luna');
$my_arr['dogs'] = array('Buddy', 'Lucy', 'Bella');
$my_arr['dolphins'] = array('Sunny', 'Comet', 'Pumpkin');
$my_arr['lizzards'] = array('Apollo', 'Eddie', 'Bruce');
//and many more lines like this
I need to sort it based on it keys using sorting array like
$order = array('lizzards', 'cats');
I want that the first item should be lizzards array, second item - cats and then all items that were not specified in $order array. How it can be done using usort / uasort / uksort functions?
You can achieve this by below code
<?php
function sortByKey(&$arr,$key_order)
{
if(count(array_intersect(array_keys($arr),$key_order))!=count($key_order))
{
return false;
}
$ordered_keys=array_merge($key_order,array_diff(array_keys($arr),$key_order));
$sorted_arr=[];
foreach($ordered_keys as $key)
{
$sorted_arr[$key]=$arr[$key];
}
$arr=$sorted_arr;
return true;
}
$my_arr=[];
$my_arr['cats'] = array('Shadow', 'Tiger', 'Luna');
$my_arr['dogs'] = array('Buddy', 'Lucy', 'Bella');
$my_arr['dolphins'] = array('Sunny', 'Comet', 'Pumpkin');
$my_arr['lizzards'] = array('Apollo', 'Eddie', 'Bruce');
$order = array('lizzards', 'cats');
if(sortByKey($my_arr,$order){
echo "Sorting done successfully";
}
else
{
echo "Sorting ignored, order element miss matched";
}
print_r($my_arr);
?>
A shorter solution using uksort:
uksort($my_arr, function ($a,$b) use ($order) {
//Look for elements indexes in the 'order' array
$aKey = array_search($a, $order);
$bKey = array_search($b, $order);
if($aKey !== FALSE && $bKey !== FALSE) {
return $aKey - $bKey;
} else if($aKey !== FALSE) {
return -1;
} else if($bKey !== FALSE) {
return 1;
}
return 0;
});
You don't need to employ a sorting algorithm at all.
If you know that the nominated elements will exist in your master array, then create an array with the leading elements' keys, then place your master array onto of that.
Code: (Demo)
var_export(array_replace(array_flip($order), $my_arr));
or
var_export(array_merge(array_flip($order), $my_arr));

PHP In_MultiArray Function

on http://php.net/manual/en/function.in-array.php - if you scroll down it gives a function to determine if a string is inside of a query in a multidimensional array. "If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time"
Here's original code(working):
function in_multiarray($elem, $array)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem)
return true;
else
if(is_array($array[$bottom]))
if(in_multiarray($elem, ($array[$bottom])))
return true;
$bottom++;
}
return false;
}
What I'm trying to do is instead of returning 'true' or 'false' - i'd like to return the ROW #. So my initial thought was to simply replace 'return true' with 'return $bottom; however it isn't returning the record number.
Modified Function (not working);
function in_multiarray($elem, $array)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem)
return $bottom;
else
if(is_array($array[$bottom]))
if(in_multiarray($elem, ($array[$bottom])))
return $bottom;
$bottom++;
}
return false;
}
Does anyone have an idea how to modify this function to return the ROW number that contains the match?
Here's a sample of the array...
$sample = array
array ("oldpage1.php","newpage1.php"),
array ("oldpage2.php","newpage2.php"),
array ("oldpage3.php","newpage3.php"),
array ("oldpage4.php","newpage4.php"),
array ("oldpage5.php","newpage5.php")
etc.
);
$row = in_multiarray($input, $sample);
Therefore if we know the row # we can fetch the new page with a simple
$newpage=$sample[$row][1]
Thanks!
It's worth noting that a function like in_array is intended to tell you whether or not a value exists inside of an array. What you're looking for seems to be a lot closer to something like array_search, which is designed to actually provide you with the key that points to a given value in the array.
However, because you're using a multi-dimensional array what you're actually looking for is the key that points to the array that contains the value. Hence we can divide and conquer this problem with two simple steps.
Map
Filter
The first step is to map a function in_array to every element in the first array (which is just another array). This will tell us which elements of the primary array contain an array that contains the value we're searching for.
$result = array_map(function($arr) use($search) {
return in_array($search, $arr, true);
}, $arr, [$searchValue]);
The second step is to then return the keys to those arrays (i.e. filter the result).
$keys = array_keys(array_filter($result));
Now you have all the keys of any matching items. If you want to apply as just one custom filter that specifies exactly where in the subarray to look, you could also do it like this.
$search = "oldpage2.php";
$sample = [
["oldpage1.php","newpage1.php"],
["oldpage2.php","newpage2.php"],
["oldpage3.php","newpage3.php"],
["oldpage4.php","newpage4.php"],
["oldpage5.php","newpage5.php"],
];
$keys = array_keys(array_filter($sample, function($arr) use($search) {
return $arr[0] === $search;
}));
var_dump($keys);
And you get...
array(1) {
[0]=>
int(1)
}
So now you know that "oldpage2.php" is in row 1 in $sample[1][0] which means you can do this to get the results out of the array.
foreach($keys as $key) {
echo "{$sample[$key][0]} maps to {$sample[$key][1]}\n";
}
Giving you
oldpage2.php maps to newpage2.php
If you want to return only the first result you could do that as well with a function like this using similar approach.
function getFirstMatch($search, Array $arr) {
foreach($arr as $key => $value) {
if ($value[0] === $search) {
return $value[1];
}
}
}
echo getFirstMatch("oldpage4.php", $sample); // newpage4.php
The Better Alternative
Of course, the better approach is to actually use the oldpage names as the actual keys of the array rather than do this expensive search through the array, because array lookup by key in PHP is just an O(1) operation, whereas this needle/haystack approach is O(N).
So we turn your $samples array into something like this and the search no longer requires any functions...
$samples = [
"oldpage1.php" => "newpage1.php",
"oldpage2.php" => "newpage2.php",
"oldpage3.php" => "newpage3.php",
"oldpage4.php" => "newpage4.php",
"oldpage5.php" => "newpage5.php",
];
Now you can just do something like $newpage = $samples[$search] and you get exactly what you're looking for. So echo $samples["oldpage2.php"] gives you "newpage2.php" directly without the intermediary step of searching through each array.
You can use the following code to get the full path to the value:
function in_multiarray($elem, $array, &$result)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem) {
array_unshift($result, $bottom);
return true;
}
else {
if(is_array($array[$bottom])) {
if(in_multiarray($elem, $array[$bottom], $result)) {
array_unshift($result, $bottom);
return true;
}
}
}
$bottom++;
}
array_shift($result);
return false;
}
$sample = array(
array ("oldpage1.php","newpage1.php"),
array ("oldpage2.php","newpage2.php"),
array ("oldpage3.php","newpage3.php"),
array ("oldpage4.php","newpage4.php"),
array ("oldpage5.php","newpage5.php")
);
$input = "newpage5.php";
$result = [];
in_multiarray($input, $sample, $result);
print_r($result);
Path is stored in $result;

PHP Function that can return value from an array key a dynamic number of levels deep

Using PHP, I would like to write a function that accomplishes what is shown by this pseudo code:
function return_value($input_string='array:subArray:arrayKey')
{
$segments = explode(':',$input_string);
$array_depth = count(segments) - 1;
//Now the bit I'm not sure about
//I need to dynamically generate X number of square brackets to get the value
//So that I'm left with the below:
return $array[$subArray][$arrayKey];
}
Is the above possible? I'd really appreciate some pointer on how to acheive it.
You can use a recursive function (or its iterative equivalent since it's tail recursion):
function return_value($array, $input_string) {
$segments = explode(':',$input_string);
// Can we go next step?
if (!array_key_exists($segments[0], $array)) {
return false; // cannot exist
}
// Yes, do so.
$nextlevel = $array[$segments[0]];
if (!is_array($nextlevel)) {
if (1 == count($segments)) {
// Found!
return $nextlevel;
}
// We can return $nextlevel, which is an array. Or an error.
return false;
}
array_shift($segments);
$nextsegments = implode(':', $segments);
// We can also use tail recursion here, enclosing the whole kit and kaboodle
// into a loop until $segments is empty.
return return_value($nextlevel, $nextsegments);
}
Passing one object
Let's say we want this to be an API and pass only a single string (please remember that HTTP has some method limitation in this, and you may need to POST the string instead of GET).
The string would need to contain both the array data and the "key" location. It's best if we send first the key and then the array:
function decodeJSONblob($input) {
// Step 1: extract the key address. We do this is a dirty way,
// exploiting the fact that a serialized array starts with
// a:<NUMBEROFITEMS>:{ and there will be no "{" in the key address.
$n = strpos($input, ':{');
$items = explode(':', substr($input, 0, $n));
// The last two items of $items will be "a" and "NUMBEROFITEMS"
$ni = array_pop($items);
if ("a" != ($a = array_pop($items))) {
die("Something strange at offset $n, expecting 'a', found {$a}");
}
$array = unserialize("a:{$ni}:".substr($input, $n+1));
while (!empty($items)) {
$key = array_shift($items);
if (!array_key_exists($key, $array)) {
// there is not this item in the array.
}
if (!is_array($array[$key])) {
// Error.
}
$array = $array[$key];
}
return $array;
}
$arr = array(
0 => array(
'hello' => array(
'joe','jack',
array('jill')
)));
print decodeJSONblob("0:hello:1:" . serialize($arr));
print decodeJSONblob("0:hello:2:0" . serialize($arr));
returns
jack
jill
while asking for 0:hello:2: would get you an array { 0: 'jill' }.
you could use recursion and array_key_exists to walk down to the level of said key.
function get_array_element($key, $array)
{
if(stripos(($key,':') !== FALSE) {
$currentKey = substr($key,0,stripos($key,':'));
$remainingKeys = substr($key,stripos($key,':')+1);
if(array_key_exists($currentKey,$array)) {
return ($remainingKeys,$array[$currentKey]);
}
else {
// handle error
return null;
}
}
elseif(array_key_exists($key,$array)) {
return $array[$key];
}
else {
//handle error
return null;
}
}
Use a recursive function like the following or a loop using references to array keys
<?php
function lookup($array,$lookup){
if(!is_array($lookup)){
$lookup=explode(":",$lookup);
}
$key = array_shift($lookup);
if(!isset($array[$key])){
//throw exception if key is not found so false values can also be looked up
throw new Exception("Key does not exist");
}else{
$val = $array[$key];
if(count($lookup)){
return lookup($val,$lookup);
}
return $val;
}
}
$config = array(
'db'=>array(
'host'=>'localhost',
'user'=>'user',
'pass'=>'pass'
),
'data'=>array(
'test1'=>'test1',
'test2'=>array(
'nested'=>'foo'
)
)
);
echo "Host: ".lookup($config,'db:host')."\n";
echo "User: ".lookup($config,'db:user')."\n";
echo "More levels: ".lookup($config,'data:test2:nested')."\n";
Output:
Host: localhost
User: user
More levels: foo

PHP count # of items in an object of a given property value

How can I count the number of items with the same folder_id# ?
Here's my list of items:
item_id=1, folder_id=1
item_id=2, folder_id=1
item_id=3, folder_id=2
item_id=4, folder_id=3
Here's my UPDATED code:
foreach($items as $item)
{
if(????) //count of $item->folder_id > 1
{
//do something to $item->folder_id=1/$item->item_id=1
}
elseif(????) // cases where $item->item_id != $item->folder_id
{
//do something else to $item->folder_id=1/$item->item_id=2
}
else
{
//do something else to $item->folder_id=2/$item->item_id=3 and folder_id=3/item_id=4
}
}
I'm interested in code that can tell me that the count for folder_id=1 is 2, the count for folder_id=2 is 1, and the count for folder_id=3 is also 1.
UPDATE: I've changed the code above to now include an elseif() because it didn't quite ask all the things I was interested in. Besides counting the # of each folder_id, I'm also interested in distinguishing cases where folder_id != item_id. This would put item_id=1, item_id=2, item_id=3/4 in their own conditional clauses and wouldn't lump item_id=1 and item_id=2 as before.
Any assistance would be greatly appreciated, thank you,
If you had an array of folder_ids, you could use array_count_values to provide exactly the result you need. So let's make an array like that out of an array of objects using array_map:
$callback = function($item) { return $item->folder_id; };
$result = array_count_values(array_map($callback, $items));
This will end up with $result being
array(
1 => 2,
2 => 1,
3 => 1,
);
You can also write the callback inline for an one-liner, or if you are on PHP < 5.3 you can write it as a free function or alternatively using create_function.
See it in action (version for PHP < 5.3).
Update: follow up
Given $results from above, your loop would be:
foreach($results as $folder_id => $count) {
if($count > 1) {
// There were $count items with folder_id == $folder_id
}
// else blah blah
}
$totals = array();
foreach($items as $item) {
$totals[$item->folder_id]++;
}
function count_items(Array $items, $folder_id) {
return count(array_filter($items,
function($item) use($folder_id) {
return $item->folder_id === $folder_id;
}
));
}
I think this is what you are looking for.
function folder_count($items, $num)
{
$cnt = 0;
foreach($items as $item)
{
if($item->folder_id > $num)
{
$cnt++;
}
}
return $cnt;
}
foreach ($items as $item)
{
if (folder_count($items, 1))
{
//do something to $item->folder_id=1/$item->item_id=1, item_id=2
}
else
{
//do something else to $item->folder_id=2/$item->item_id=3 and folder_id=3/item_id=4
}
}

Categories