首页 > 解决方案 > 数组数组到php中的对象数组

问题描述

我需要将数组数组转换为对象数组

$data=array(
    ["GOA518232","20190301","2019-03-01","shantnu kumar","20000","12","20000","Upward Term Loan","","","Indiabulls Consumer Finance Limited"],
    ["GOA473214","20190304","2019-03-04","KANNAN M KANNAN","25000","12","18000","Upward Term Loan","","","Gestamp Automotive Chennai Pvt Ltd"],
    ["GOA441862","20190308","2019-03-08","veeru biradar","25000","12","17400","Upward Term Loan","","","Tequnic Control Facility Management"],
    ["GOA291263","20190308","2019-03-08","pavan guptha","50000","24","22000","Upward Term Loan","","","Hcl Technologies Limited"]
);

预期输出

[
    {"GOA518232","20190301","2019-03-01","shantnu kumar","20000","12","20000","Upward Term Loan","","","Indiabulls Consumer Finance Limited"},
    {"GOA473214","20190304","2019-03-04","KANNAN M KANNAN","25000","12","18000","Upward Term Loan","","","Gestamp Automotive Chennai Pvt Ltd"},
    {"GOA291263","20190308","2019-03-08","pavan guptha","50000","24","22000","Upward Term Loan","","","Hcl Technologies Limited"}
]

我试过下面的解决方案

$new_array = array();
foreach ($data as $obj)
{
    $new_array[] = (object)$obj;
}
print_r($new_array);

function ToObject($Array) { 

    // Create new stdClass object 
    $object = new stdClass(); 

    // Use loop to convert array into 
    // stdClass object 
    foreach ($Array as $key => $value) { 
        if (is_array($value)) { 
            $value = ToObject($value); 
        } 
        $object->$key = $value; 
    } 
    return $object; 
} 

标签: phparraysobject

解决方案


使用json_encode()

foreach($data as &$arr){
    $arr = json_encode($arr,JSON_FORCE_OBJECT);
}

print_r($data);

输出:- https://3v4l.org/7JpHU


推荐阅读