Friday 31 August 2018

PHP - Create a multidimensional array from a one-dimensional array

Ok, so i have this string array that looks something like this:

myArray[0] = "a0,b0,c0,d0"
myArray[1] = "a1,b1,c1,d1"
myArray[2] = "a2,b2,c2,d2"
myArray[3] = "a3,b3,c3,d3"
etc...

I want to create a multidimentional array that uses the first part of each element as "key". In short:
myMultiArray:
x/y|  0   |  1   |  2   |  3   |
------------------------
 0 | "a0" | "a1" | "a2" | "a3" |
 1 | "b0" | "b1" | "b2" | "b3" |
 2 | "c0" | "c1" | "c2" | "c3" |
 3 | "d0" | "d1" | "d2" | "d3" |

this is what I've got:
 private String[,] resultsParser(String[] inputArray)
    {
        String[] splittedString = null;
        String[,] outputString = null;
        for (int i = 0; i < inputArray.Length; i++ )
        {
            splitString = inputArray[i].Split(',');
            for (int j = 0; j < outputArray.GetLength(0); j++)
            {
                if (splitString[0] == outputArray[j, 0])
                {
                    for (int k = 1; k < splitString.Length; k++)
                    {
                        outputArray[j, k] = splitString[k];
                    }
                }
            }
            for (int k = 0; k < splitString.Length; k++)
            {
                outputArray[outputArray.GetLength(0), k] = splitString[k];
            }
        }
        return outputArray;
    }

  • Problem1: it doesn't work
  • Problem2: the code is fugly
Is there some easy way of doing this?

It seems to me you need to separate this into two stages:
  • Determining the size
  • Splitting each row and copying the results
Each of these is reasonably simple, but you'll find the code much simpler if you separate them. Something like:
public static string[,] SplitResults(string[] input)
{
    int columns = input[0].Split(',').Length;
    string[,] output = new string[input.Length, columns];

    for (int row = 0; row < input.Length; row++)
    {
        string[] split = input[row].Split(',');
        for (int column = 0; column < columns; column++)
        {
            output[row, column] = split[column];
        }
    }
    return output;
}

However, you should add validation:
  • input should not be null
  • input should not be empty
  • Every row should be the same size
Note that the code above splits the first row twice (once to find the size, and once to populate the data). While you could fix that to be more efficient, it would make the code more ugly - I wouldn't do it unless you really found it to be a bottleneck.

0 comments:

Post a Comment