Viewed   73 times

I have the following array:

Array
(
    [0] => INBOX.Trash
    [1] => INBOX.Sent
    [2] => INBOX.Drafts
    [3] => INBOX.Test.sub folder
    [4] => INBOX.Test.sub folder.test 2
)

How can I convert this array to a multidimensional array like this:

Array
(
    [Inbox] => Array
        (
            [Trash] => Array
                (
                )

            [Sent] => Array
                (
                )

            [Drafts] => Array
                (
                )

            [Test] => Array
                (
                    [sub folder] => Array
                        (
                            [test 2] => Array
                                (
                                )

                        )

                )

        )

)

 Answers

2

Try this.

<?php
$test = Array
(
    0 => 'INBOX.Trash',
    1 => 'INBOX.Sent',
    2 => 'INBOX.Drafts',
    3 => 'INBOX.Test.sub folder',
    4 => 'INBOX.Test.sub folder.test 2',
);

$output = array();
foreach($test as $element){
    assignArrayByPath($output, $element);   
}
//print_r($output);
debug($output);
function assignArrayByPath(&$arr, $path) {
    $keys = explode('.', $path);

    while ($key = array_shift($keys)) {
        $arr = &$arr[$key];
    }
}

function debug($arr){
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
}
Sunday, October 23, 2022
 
4

You need to iterate over your results, adding a new entry to the output when you encounter a new team, or updating the points value when you find the same team again. This is most easily done by initially indexing the output by the team name, and then using array_values to re-index the array numerically:

$teams = array();
foreach ($results as $result) {
    $team = $result['team'];
    if (!isset($teams[$team])) {
        $teams[$team] = array('team' => $team, 'points' => $result['punti']);
    }
    else {
        $teams[$team]['points'] += $result['punti'];
    }
}
$teams = array_values($teams);
print_r($teams);

Output (for your sample data):

Array
(
    [0] => Array
        (
            [team] => Red Bull Racing
            [points] => 418
        )
    [1] => Array
        (
            [team] => Scuderia Ferrari
            [points] => 353
        )
    [2] => Array
        (
            [team] => Mercedes-AMG
            [points] => 516
        )
    [3] => Array
        (
            [team] => Racing Point F1
            [points] => 147
        )
    [4] => Array
        (
            [team] => Haas F1
            [points] => 127
        )
)

Demo on 3v4l.org

Friday, August 12, 2022
 
3

As simple as:

$arr = array(
    "action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
    "action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
    "action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",
);
  
$data = [];
foreach ($arr as $line) {
    $newItem = [];
    foreach (explode(';', $line) as $item) {
        $parts = explode(':', $item);
        $newItem[trim($parts[0])] = trim($parts[1]);
    }
    $data[] = $newItem;
}

print_r($data);

Fiddle here.

Monday, December 26, 2022
3

You can do it like this, do the calculation from the innermost of the array. Check the demo.

<?php
function f(&$array)
{
    foreach($array as $k => &$v)
    {
        if(is_array($v))
        {
            if(count($v) == count($v, 1))
            {
                unset($array[$k]);
                if($k == 'sum')
                {
                    $v =  array_sum($v);
                    $array[] = $v;

                }elseif($k == 'multiply'){
                    $v = array_product($v);
                    $array[] = $v;
                }else{

                    foreach($v as $vv)
                        $array[] = $vv;
                }
            }else
                f($v);
        }
    }
}

while(count($array) != count($array, 1))
{
    f($array);
}

print_r($array);

Note:

traverse array from outer to inner
traverse array from inner to outer

Monday, November 14, 2022
 
3

Well do you need 2D array for your String? Why not store a String like "ABCDEFGHI" and access it as if it was 3x3 2D array?

Map x,y "coordinates" to index.

public class Char2DDemo
{
    public static int ROWS = 3;
    public static int COLS = 3;

    public static class Char2D
    {
        private StringBuilder sb = null;
        private int ROWS;
        private int COLS;

        public Char2D(String str, int rows, int cols)
        {
            this.sb = new StringBuilder(str);
            this.ROWS = rows;
            this.COLS = cols;
        }

        public StringBuilder getSb()
        {
            return sb;
        }

        public int getRowCount()
        {
            return ROWS;
        }

        public int getColCount()
        {
            return COLS;
        }

        public int xy2idx(int x, int y)
        {
            int idx = y * getRowCount() + x;
            return idx;
        }

        public int idx2x(int idx)
        {
            int x = idx % getRowCount();
            return x;
        }

        public int idx2y(int idx)
        {
            int y = (idx - idx2x(idx)) / getRowCount();
            return y;
        }

        public Character getCh(int x, int y)
        {
            return getSb().charAt(xy2idx(x, y));
        }

        public void setCh(Character ch, int x, int y)
        {
            getSb().setCharAt(xy2idx(x, y), ch);
        }
    }

    public static void main(String[] args) throws java.lang.Exception
    {
        String test = "ABC"
                    + "DEF"
                    + "GHI";

        Char2D c2d = new Char2D(test, 3, 3);

        System.out.println("Before " + c2d.getSb());
        System.out.println("at [2][2] " + c2d.getCh(2, 2));
        c2d.setCh('J', 0, 0);
        c2d.setCh('K', 2, 2);
        c2d.setCh('M', 1, 1);        
        System.out.println("After " + c2d.getSb());
        System.out.println("at [1][0] " + c2d.getCh(1, 0));
    }
}

Output:

Before ABCDEFGHI
at [2][2] I
After JBCDMFGHK
at [1][0] B
Tuesday, August 23, 2022
 
mgosk
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share