logo
down
shadow

PHP - Recursively set each array element's key to the value of a child element when given the childs key name


PHP - Recursively set each array element's key to the value of a child element when given the childs key name

Content Index :

PHP - Recursively set each array element's key to the value of a child element when given the childs key name
Tag : php , By : Stuka
Date : November 22 2020, 02:59 PM

around this issue This was trickier than I first imagined but I believe I have a messy solution.
First of all, this is the data I am working with. dumpr is a custom function that formats var_dump better.
$arrayKeyOrder = array(
    'site_id',
    'language_id'
);

$original = array(
    array(
        'site_id' => '0',
        'language_id' => '1',
        'name' => 'sitename',
        'description' =>'site desc',
    ),

    array(
        'site_id' => '0',
        'language_id' => '2',
        'name' => 'sitename',
        'description' =>'site desc',
    ),

    array(
        'site_id' => '1',
        'language_id' => '1',
        'name' => 'sitename',
        'description' =>'site desc',
    ),

    array(
        'site_id' => '2',
        'language_id' => '1',
        'name' => 'sitename',
        'description' =>'site desc',
    ),
);

$zipped = doZip($original, $arrayKeyOrder);
$unzipped = unZip($zipped, $arrayKeyOrder);

dumpr($original);
dumpr($zipped);
dumpr($unzipped);
function doZip($arrayRows, $arrayKeyOrder){

    // Prepare resulting array
    $arrayResult = array();

    // Cycle the input array
    foreach($arrayRows as $someRow){
        // We will acomplish this using references
        $current = &$arrayResult;

        // get the current level
        foreach($arrayKeyOrder as $someKey){
            $someValue = $someRow[$someKey];
            if(isset($current[$someValue])){
                $current = &$current[$someValue];
            }else{
                $current[$someValue] = array();
                $current = &$current[$someValue];
            }
            unset($someRow[$someKey]);
        }

        $current = $someRow;
    }

    return $arrayResult;
}


function unZip($arrayRows, $arrayKeyOrder, $arrayValues = array(), $depth = 0){

    $arrayResults = array();

    if($depth < count($arrayKeyOrder)){
        foreach($arrayRows as $key => $value){
            $arrayValues[$depth] = $key;
            $arrayResults[] =  unZip($value, $arrayKeyOrder, $arrayValues, $depth + 1);
        }
    }else{
        $extra = array_combine($arrayKeyOrder, $arrayValues);
        $result = array_merge($extra, $arrayRows);
        return $result;
    }

    if($depth == 0){
        for($i = 1; $i < count($arrayKeyOrder); $i++){
            $arrayResults = call_user_func_array('array_merge', $arrayResults);
        }        
    }

    return $arrayResults;
}
/vhost/virtual/sandbox/public/index.php:54
array(4) {
    [0] = array(4) {
        [site_id] = string(1) "0"
        [language_id] = string(1) "1"
        [name] = string(8) "sitename"
        [description] = string(9) "site desc"
    }
    [1] = array(4) {
        [site_id] = string(1) "0"
        [language_id] = string(1) "2"
        [name] = string(8) "sitename"
        [description] = string(9) "site desc"
    }
    [2] = array(4) {
        [site_id] = string(1) "1"
        [language_id] = string(1) "1"
        [name] = string(8) "sitename"
        [description] = string(9) "site desc"
    }
    [3] = array(4) {
        [site_id] = string(1) "2"
        [language_id] = string(1) "1"
        [name] = string(8) "sitename"
        [description] = string(9) "site desc"
    }
}

/vhost/virtual/sandbox/public/index.php:55
array(3) {
    [0] = array(2) {
        [1] = array(2) {
            [name] = string(8) "sitename"
            [description] = string(9) "site desc"
        }
        [2] = array(2) {
            [name] = string(8) "sitename"
            [description] = string(9) "site desc"
        }
    }
    [1] = array(1) {
        [1] = array(2) {
            [name] = string(8) "sitename"
            [description] = string(9) "site desc"
        }
    }
    [2] = array(1) {
        [1] = array(2) {
            [name] = string(8) "sitename"
            [description] = string(9) "site desc"
        }
    }
}

/vhost/virtual/sandbox/public/index.php:56
array(4) {
    [0] = array(4) {
        [site_id] = int(1) 0
        [language_id] = int(1) 1
        [name] = string(8) "sitename"
        [description] = string(9) "site desc"
    }
    [1] = array(4) {
        [site_id] = int(1) 0
        [language_id] = int(1) 2
        [name] = string(8) "sitename"
        [description] = string(9) "site desc"
    }
    [2] = array(4) {
        [site_id] = int(1) 1
        [language_id] = int(1) 1
        [name] = string(8) "sitename"
        [description] = string(9) "site desc"
    }
    [3] = array(4) {
        [site_id] = int(1) 2
        [language_id] = int(1) 1
        [name] = string(8) "sitename"
        [description] = string(9) "site desc"
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

XPath to select element based on childs child value


Tag : xml , By : Jarques
Date : March 29 2020, 07:55 AM
wish helps you Trying to select an element based on the value of one of it's childrens childrens , Almost there. In your predicate, you want a relative path, so change
./book[/author/name = 'John'] 
./book[author/name = 'John'] 
./book[./author/name = 'John'] 

PHP : Rename keys of associative array to the value of a child element when given the childs key name


Tag : php , By : Paolo
Date : March 29 2020, 07:55 AM
this will help Is there a PHP function I've missed that will change the keys of the parent array when given the key name of its child(associative array) or is there at least an alternative to a foreach loop which i am using at the moment to change the keys. , If I understand the question correctly, something like:
$arr = array_combine(
    array_column($arr, 'name'),
    $arr
);
array(3) {
  ["one"]=>
  array(2) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(3) "one"
  }
  ["two"]=>
  array(2) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(3) "two"
  }
  ["three"]=>
  array(2) {
    ["id"]=>
    int(3)
    ["name"]=>
    string(5) "three"
  }
}

How do you recursively select all child elements under a parent element?


Tag : tsql , By : user167963
Date : March 29 2020, 07:55 AM
Any of those help Let's say we've got this table:
Declare @YourTable Table ([NAME] varchar(50),[ID] varchar(50),[ManagerID] varchar(50))
Insert Into @YourTable Values
 ('John',1,3)
,('Sally',2,3)
,('Paul',3,4)
,('Jane',4,5)
,('Jennifer',5,8)
,('Boss',8,null) 


Declare @Top    int         = 4      --<<  NULL for Full Hier
Declare @Nest   varchar(25) = '|-----'  --<<  Optional: Added for readability

;with cteP as (
      Select Seq  = cast(10000+Row_Number() over (Order by Name) as varchar(500))
            ,ID
            ,ManagerId 
            ,Lvl=1
            ,Name 
      From   @YourTable 
      Where  IsNull(@Top,-1) = case when @Top is null then isnull(ManagerId ,-1) else ID end
      Union  All
      Select Seq  = cast(concat(p.Seq,'.',10000+Row_Number() over (Order by r.Name)) as varchar(500))
            ,r.ID
            ,r.ManagerId 
            ,p.Lvl+1
            ,r.Name 
      From   @YourTable r
      Join   cteP p on r.ManagerId  = p.ID)
Select A.ID
      ,A.ManagerId 
      ,A.Lvl
      ,Name = Replicate(@Nest,A.Lvl-1) + A.Name
 From  cteP A
 Order By Seq
ID  ManagerId   Lvl Name
4   5           1   Jane
3   4           2   |-----Paul
1   3           3   |-----|-----John
2   3           3   |-----|-----Sally

recursively get CSS from an element and all the childs


Tag : javascript , By : Alpinfish
Date : March 29 2020, 07:55 AM
help you fix your problem i came up with a solution that maybe give you idea about how improve your code. In order to test driving this code I've made an element that have some children in different depths and this code traverse all children by their depth in recursive way to find/get their css. After that, all founded css plus the element name will storage in an object (JSON like) for later use.
Please Note:
one : {
  display: "block",
  position: "relative"
}
two : {
  display: "inline-block",
  font-family: "Montserrat"
}
three_1 : {
  display: "table",
  position: "absolute",
  left: "0px"
}
four_1 : {
  display: "table-cell",
  position: "relative"
}
three_2 : {
  display: "table",
  position: "absolute",
  right: "0px"
}
four_2 : {
  display: "table-cell",
  position: "relative"
}
<div class="one">
    <div class="two">
        <div class="three_1">
            <div class="four_1"></div>
        </div>
        <div class="three_2">
            <div class="four_2"></div>
        </div>
    </div>
</div>
.one {display:block;position:relative;}
.two {display:inline-block;font-family:'Montserrat';}
.three_1 {display:table;position:absolute;left:0;}
.three_2 {display:table;position:absolute;right:0;}
.four_1 {display:table-cell;position:relative;}
.four_2 {display:table-cell;position:relative;}
function convertObjlike(css) {
    var s = {};
    if (!css) return s;
    css = css.split("; ");
    for (var i in css) {
        var l = css[i].split(": ");
        s[l[0].toLowerCase()] = (l[1]);
    }
    return s;
}

function getCss(a) {
    var sheets = document.styleSheets, o = {};
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a === rules[r].selectorText) {
                o = convertObjlike(rules[r].style.cssText);
            }
        }
    }
    return o;
}

var anObject = {};
function styleRecursive(element){
  anObject[element.className] = (getCss('.'+element.className));
  var children = element.children;

  for (var i = 0; i < children.length; i++) {
    styleRecursive(children[i])
  }
}

styleRecursive( document.querySelector('.one') );
console.log(anObject);

JS Recursively find element in parent-child array


Tag : javascript , By : 40a
Date : March 29 2020, 07:55 AM
I wish this helpful for you The result of the recursive call must be returned, for it to propagate up to the point of invocation and be returned as the result.
function findNode(nodes, predicate) {
    for (const node of nodes) {
        if (predicate(node)) return node

        if (node.rows) {
            let match = findNode(node.rows, predicate)
            if (match) return match
        }
    }
}

const tree = [{
    value: 'a',
    rows: [{
        value: 'b'
    }]
}, {
    value: 'c',
    rows: [{
        value: 'd',
        rows: [{
            value: 'e'
        }]
    }]
}]

const result = findNode(tree, ({value}) => value === 'e')

console.log(result)
Related Posts Related QUESTIONS :
  • php/mysql. selecting 2 common fields in 2 tables
  • Expand an string based on values in an array in PHP
  • When you absolutely have to manually escape SQL in CakePHP 3.4.7
  • Htaccess redirecting wrong page
  • Laravel Optional WHERE clause
  • PHP unpack overlfow variable memory limit
  • How to check the URL's structure using PHP preg_match?
  • PHP preg_replace - text will not be recognized
  • Show image from other domain without showing the domain name - PHP
  • How to run and watch local server at the same time?
  • Access form request from Observer laravel
  • single quote problem with preg_replace_callback
  • How to Create A Unique URL for each product enquiry form for Google Analytics Tracking
  • Laravel email configuration: what am I missing?
  • Assign indexed array values to multidimensional array?
  • Custom WordPress stylesheet not loading
  • Data attribute only returning first value
  • How to list all roles with Permissions,in spatie permission Package?
  • How to achieve this number pattern with n input
  • How to iterate array inside array data in laravel ,output are given below
  • To get output of movie with its genre
  • Extracting some data from a JS object literal string in PHP using Regex
  • axios and vuex are deleting wrong index in array
  • Setting empty CURLOPT_POSTFIELDS
  • Laravel 5.8 use subdomain as API endpoint beside domain.com/api
  • Error while add data in database SQL Server 2016
  • Does PhpStorm allow to skip PHPDoc tags when type hints is declared?
  • html classes are changed to Attributes
  • Using json to import multidimensional data
  • passing data from the view to the controller, where the data comes from another controller
  • How to extract integer and decimal numbers in PHP string correctly?
  • Parsing Sub-Object from an XML Feed with objects
  • Getting error "Unknown column 'text' in 'field list'"
  • How to properly get onedrive access token via php and curl
  • How to add spell check to a php function
  • Is it posible to create css rules with php?
  • Pretty URL with $_GET method
  • Wordpress always load same page - index.php
  • Find value in array and return with new from different array
  • PHP multiple file upload with different keys
  • Can't modify times one a time without weird errors
  • Get size of scraped image with domcrawler (Goutte)
  • Laravel - Ordering a collection of models
  • PHP Fatal error: Uncaught Error: Call to a member function setFetchMode() on boolean
  • Strict Standards: Only variables should be passed by reference in /main_dir/sub_dir/backup.php
  • Uncaught Google_Exception: (update) unknown parameter: 'copyRequiresWriterPermission'
  • Laravel 5 form does not redirect with old input
  • How to get values greater than or equal to in Mysql database sql when its a value like 1:00 PM?
  • PHP datediff overday issue
  • Masking an auto incrementing primary key
  • How to grab a String BEFORE a certain word
  • ZF2 Routing Multiple Controllers based on route constraints
  • How to deregister/dequeue jquery.sticky.js in Elementor (Pro)?
  • How to fix errors counting words in text plain with PHP?
  • How to get View data in Laravel in custom helper or directive
  • Creating a new data entry into a database with eloquent and trying to access the variable in the url
  • How to test authentication using Laravel Dusk?
  • PHP parse_str not getting all $_GET variables
  • Variable issues in php class
  • Get orders between dates in Codeigniter
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com