Passing a Python list to php

后端 未结 4 1037
失恋的感觉
失恋的感觉 2020-12-30 12:57

I\'m very new to php and I\'ve been spending quite some type understanding how to pass arguments from Python to php and conversely. I now know how to pass single variables,

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 13:18

    Apparently your question was misleading. Was redirected here thinking this a solution for converting python lists to php array.

    Posting a naive solution for ones wanting to convert lists to php array.

    // Sample python list 
    $data = '[["1","2","3","4"],["11","12","13","14"],["21","22","23","24"]]';
    
    // Removing the outer list brackets
    $data =  substr($data,1,-1);
    
    $myArr = array();
    // Will get a 3 dimensional array, one dimension for each list
    $myArr =explode('],', $data);
    
    // Removing last list bracket for the last dimension
    if(count($myArr)>1)
    $myArr[count($myArr)-1] = substr($myArr[count($myArr)-1],0,-1);
    
    // Removing first last bracket for each dimenion and breaking it down further
    foreach ($myArr as $key => $value) {
     $value = substr($value,1);
     $myArr[$key] = array();
     $myArr[$key] = explode(',',$value);
    }
    
    //Output
    Array
    (
    [0] => Array
        (
            [0] => "1"
            [1] => "2"
            [2] => "3"
            [3] => "4"
        )
    
    [1] => Array
        (
            [0] => "11"
            [1] => "12"
            [2] => "13"
            [3] => "14"
        )
    
    [2] => Array
        (
            [0] => "21"
            [1] => "22"
            [2] => "23"
            [3] => "24"
        )
    
    )
    

提交回复
热议问题