Mishra Shreyanshu
Mishra Shreyanshu

Reputation: 644

Equivalent for LinkedHashMap in php?

My application is currently on java and I am sending a LinkedHashMap (getting Data from Excel) to a service. Now I am converting my application to php.

I need to create a LinkedHashMap in php.

String data[][];  // Excel data in the form of 2-D Array.
LinkedHashMap<Integer, ArrayList> mapToSend = null;
mapToSend = new LinkedHashMap<Integer, ArrayList>();


for (int i = 0; i < data[0].length; i++) {
    ArrayList<String> ar = new ArrayList<String>();
    for (int j = 0; j < numberOfRecords; j++) {
        if (data[j][i] != null) {
             data[j][i] = data[j][i].toString();

            ar.add(data[j][i]); // Add in array through coloumnwise
            } else {
            ar.add("Empty");
        }
    }
    mapToSend.put(i, ar); // making a map like {0=[coloumn data1],1=[coloumn data2]....}
}

This is how I create the map to sent to my service.

I am using PHPExcel to read data from Excel.

i need to create a map and send it to a service. please Suggest.

Upvotes: 3

Views: 913

Answers (1)

button
button

Reputation: 656

The code you provided actually looks more like a 'normal' array in PHP. Arrays in PHP can act as arrays in the more traditional sense, maps like your Java one (except they still possess order over and above that implied by the keys themselves).

Your implementation looks like the below in PHP. There's a number of assumptions about the data input and required business logic there, I would write some test cases that define cases such as 'true', 0, '' against the required output. Basically, watch out for all the ways strval($data[$j][$i]) can behave differently.

You are creating a map from integer => string in Java, but to me it just looks like an normal array.

$data = array();

//the input data
$data[] = array("val1", "val2");
$data[] = array("val3", 0);
$data[] = array("val4");
$data[] = array("val5", "");
$data[] = array(0, "val6");

$numberOfRecords = count($data); //assuming all of it...

$mapToSend = array();

for($i = 0; $i < count($data[0]); $i++) {
        $ar = array();
        for($j = 0; $j < $numberOfRecords; $j++) {
                if( ($val = strval($data[$j][$i])) != "" ) {//the comparison of your choice, depending on the logic/input
                        $ar[] = $val;
                } else {
                        $ar[] = "Empty";
                }
        }
        $mapToSend[] = $ar; //naturally, this will have indexes 0, 1, 2...
}

var_dump( $mapToSend );

Outputs:

array(2) {
  [0]=>
  array(5) {
    [0]=>
    string(4) "val1"
    [1]=>
    string(4) "val3"
    [2]=>
    string(4) "val4"
    [3]=>
    string(4) "val5"
    [4]=>
    string(1) "0"
  }
  [1]=>
  array(5) {
    [0]=>
    string(4) "val2"
    [1]=>
    string(1) "0"
    [2]=>
    string(5) "Empty"
    [3]=>
    string(5) "Empty"
    [4]=>
    string(4) "val6"
  }
}

Upvotes: 1

Related Questions