Simplify a multidimensional array in PHP

Simplify a multidimensional array in PHP

Content Index :

Simplify a multidimensional array in PHP
Tag : php , By : user165871
Date : December 18 2020, 12:00 PM

it should still fix some issue I've received and XML, converted it into an array for usage. The XML comes in unpredictable multi dimension when I convert it into array. Had been looking around but could not find a suitable solution. An alternative is to simplify the converted array. , This should work as expected :
function recursive_skip(array $ary) {
    foreach($ary as $k => &$v) {
        if (is_array($v)) {
            // Skip it
            $v = $v[0];
        if (is_array($v)) {
            // If current array item is an array itself, recursively call the function on it
            $v = recursive_skip($v);

    // Return updated array to calling context
    return $ary;


$source = Array(
    'GetMLCBRes' => Array(Array(
        'Ord' => Array(Array(
                        'OrdId' => Array('DP Order ID')
        'ReqInf' => Array(Array(
                        'ReqDat' => Array('Date of Request')
        'Res' => Array('PDF Report')

$dest = recursive_skip($source);

No Comments Right Now !

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

Share : facebook icon twitter icon

Simplify looping through an array which could be flat or multidimensional

Tag : php , By : user161314
Date : March 29 2020, 07:55 AM
With these it helps Often, I will have an array holding a set of values each of which I need to process. Sometimes, the array will only hold a single set, in which case each value needs to be put through the process. Other times, the array will hold many sets, in which case each value will be an array and each value of those arrays will need to be processed. Here is an example: , Wrap the single value into an array, then proceed as usual:
foreach($array as $key => $value) {

    if(!is_array($value)) $value = array($value);

    foreach($value as $subkey => $subvalue) {
        //Process $value/$subvalue here    

PHP Array convert and simplify multidimensional array

Tag : php , By : pacorro2000
Date : March 29 2020, 07:55 AM
I wish this help you So just iterate over the original array and assemble the result; something like this:
$categories = array();

foreach ($data as $itemId => $itemData) {
        foreach ($itemData['categories'] as $categoryId) {
                $categories[$categoryId][] = $itemId;

Simplify a multidimensional array to a string

Tag : php , By : Ram
Date : March 29 2020, 07:55 AM
Hope this helps You can use array_column followed by join or implode
Try this :
$string = join(',', array_column($array, 'tag_name'));
    [0] => tag-1
    [1] => tag-2
    [2] => tag-3
//$string = "tag-1,tag-2,tag-3"

php - Simplify select from multidimensional array according the preferred group of row values

Tag : php , By : eataix
Date : March 29 2020, 07:55 AM
it should still fix some issue On output, I want an array with row per unique height. If there is row with same ext and height (like in 0, 6) on input, just take the first value. If there are rows with the same height prefer jpg over png over gif over the rest (3, 9, 10). , Here is a simple function that can solve your problem
function filterAndSort($input){
    $output = array();
    $extensionsWeght = array(
        'jpg' => 0,
        'png' => 1,
        'gif' => 2
    foreach ($input as $v) {
        //Edit 1:  skip if no hieght is present
        if (!isset($output[$v['height']])) {
            //If it's a new height, add it
            $output[$v['height']] = $v;
        } else {
            //else, choose the prefered ext [if they have the same ext, the first entry is already choosen]
            if ($extensionsWeght[$output[$v['height']]['ext']] > $extensionsWeght[$v['ext']]) {
                $output[$v['height']] = $v;
    //Sort the ouput by height key
    // usort($output, function($a, $b) {
    //    return $a['height'] - $b['height'];

    //Edit 2 :

    //For sorting the array, as it is indexed with the height key,
    // you can use the built in functions to sort it. (ksort for this case)

    return array_values($output);

How can manage multidimensional array in foreach() for tree view while multidimensional array form of multi level

Tag : php , By : MK.
Date : March 29 2020, 07:55 AM
wish of those help Indeed array_filter does not work recursively.
Here is a recursive function that does the job of taking out null values:
function array_filter_recursive($arr, $cb = null) {
    if (empty($cb)) {
        $cb = function ($el) {
            return $el;
    $result = [];
    foreach($arr as $key => $val) {
        if (is_array($val)) $val = array_filter_recursive($val, $cb);
        if ($cb($val)) $result[$key] = $val;
    return $result;
$result.= "{ 'name': '".$child_4."', 'title': '".$child_4."' ,";
function convert($arr) {
    $result = [];
    $byId = [];

    function recurse(&$result, &$byId, $arr) {
        if (!is_array($arr)) return;
        if (isset($arr["gcn_id"])) {
            $parent = $arr["referral_id"];
            $record = [
                "name" => $arr["fullname"],
                "title" => $arr["gcn_id"]
            $byId[$arr["gcn_id"]] = &$record; 
            if (isset($byId[$parent])) {
                $byId[$parent]["children"][] = &$record;
            } else {
                $result[] = &$record;
        } else {
            foreach($arr as $child) {
                recurse($result, $byId, $child);

    recurse($result, $byId, $arr);    
    return $result;

$result = json_encode(convert($legs), JSON_PRETTY_PRINT);

echo $result;
        "name": "Wendy-Lynn Barr",
        "title": 11312,
        "children": [
                "name": "Pauline Blake",
                "title": 11303
        "name": "Ed Kilgour",
        "title": 5064,
        "children": [
                "name": "Craig Corbitt",
                "title": 11302,
                "children": [
                        "name": "Kristi  Iles",
                        "title": 5175,
                        "children": [
                                "name": "Joshua  Iles",
                                "title": 6013
                        "name": "Chris Chowning",
                        "title": 6308,
                        "children": [
                                // ...etc
Related Posts Related QUESTIONS :
  • Add a custom text to WooCommerce cart items if the product has a specific shipping class
  • Error connecting to CommissionJunction Token : [60] SSL certificate problem: unable to get local issuer certificate
  • How do I add a new key value pair to an object in PHP?
  • Http post request to php with dart
  • How to add a route in with blade into parameters of a component
  • How can i get the source of a 777 - CHMOD php file?
  • Convert 2010-04-16 16:30:00 to "Tomorrow Afternoon"
  • How can I hide a $_GET variable to be more secured in PHP?
  • Login to Gmail Inbox using Curl?
  • Upload Excel or CSV file to MySQL with PHP
  • Outlook Marking Email as Junk Email
  • Upload an image using class.upload.php via AJAX, display image in form using jQuery
  • mysql_connect() causes page to not display (WAMP)
  • How to limit a users uploaded image size using PHP
  • What's the difference whether or not to run PHP in safe mode?
  • Logging in to a website cURL
  • Using php to create a password system with chinese characters
  • PHP is not called properly in IE using set interval function in Javascript
  • How to read pdf, ppt, xl, doc files content into a string in php/python
  • php script for currency conversion
  • In PHP... best way to turn string representation of a folder structure into nested array
  • PayPal for Indian Rupees (INR) any solution
  • PHP Deployment to Live Server
  • Ideal Multi-Developer Lamp Stack?
  • How can I save an image from a file input field using PHP & MySQL?
  • Warning: array_multisort() [function.array-multisort]: Argument #1 is expected to be an array or a sort flag in
  • Connecting to external MySQL DB from a web server not running MySQL
  • Is it possible to add custom fields to a Drupal taxonomy term?
  • PHP 6.0 - Roadmap?
  • jQuery wait for ajax call to be over before continuing
  • checkUnique function?
  • How to define an n-m relation in doctrine?
  • Sort the unsorted text file and rewrite to same text file in sorted order
  • Version control a content management system?
  • How can i run Single PHP File using apache-tomcat-6.0.18?
  • Array of objects is empty when I come to retrieve one from the array
  • PHP Library: Calculate a bounding box for a given lat/lng location
  • Good Wordpress Theme/plugin for showing off code examples and scripts
  • Replace all spaces and special symbols with dash in URL using PHP language
  • globally get any field value in user table of logged in user
  • Can you get a job if you know XHTML, CSS and Basic PHP?
  • HTML Upload Form will only upload files found in the directory of the PHP file
  • Determine if a PHP array uses keys or indices
  • Are frameworks really necessary for beginners/intermediates?
  • PHP File Downloading Questions
  • Who owns a php exec tar extracted file?
  • Best way to get timezone of user based on area code
  • Mysql BETWEEN clause being ignored. No syntax error
  • Zend Framework: Getting request object in bootstrap
  • PHP + GD: imagetruecolortopalette not keeping transparency
  • Good Guide For Web App Security?
  • Creating a new wordpress post from twitter tweets
  • Query to show images with recent posts in Wordpress sidebar/widget
  • select & print multiple value from dropdown list
  • Storing a digital signature for bookings on a web based system
  • How to generate all permutations of a string in PHP?
  • How do I get the PostgreSQL PHP extension working on Windows?
  • Parsing WordPress XML, slash:comments syntax?
  • Hide order status in the status dropdown on WooCommerce admin orders page
  • PHP Converting Hex string to Byte Array - converting VB.Net to PHP
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com