我想构建一个对象(用于角度),所以它看起来像这样
user:{
{education:
{high school:'some school'},
{faculty:'faculty of science'}
},
{skills:
{skill1:'sk1'},
{skill2:'sk2'}
}
}
这是我的php和mysql查询:
$testArr = array();
$user = new stdClass();
$params = DB::select( DB::raw("SELECT param.*, sys_param_values.*,param_value.*,type_user.*,
param.name AS paramName,
doc_param.name AS docParamName
FROM param
LEFT JOIN doc_param ON param.doc_param_id = doc_param.id
LEFT JOIN sys_param_values ON param.id = sys_param_values.param_id
LEFT JOIN param_value ON sys_param_values.value_ref = param_value.id
LEFT JOIN type_user ON sys_param_values.ref_user_id = type_user.id"));
查询结果:
"params":[{"id":21,"name":"faculty","type_id":5,"doc_param_id":14,"created_at":"2015-05-17 14:13:12","updated_at":"2015-06-04 08:19:43","doc_type":12,"ref_user_id":21,"param_id":48,"iteration":null,"value_short":null,"value_long":null,"value_ref":74,"value":"some High","type":"tech-admin","email":"xxxxxxx8@gmail.com","password":"$2y$10$6L8voJ3DgZuADHZLaBh4jei\/U.svVdcN4B02XFc9mF\/p8m5RpfJtG","password_new":null,"first_name":"jon","last_name":"snow","street_1":"shiv","street_2":"tey","city":"123456","state":"aa","zipcode":"47252","country":"usa","phone_1":"123456","phone_2":"123456","mobile":"123456789","date_of_birth":"2015-05-18 11:25:42","registration":"0000-00-00 00:00:00","last_login":"2015-05-20 09:14:52","send_newsletters":1,"send_notifications":1,"remember_token":"dtlimLNZBWdCxcqKR7NdDblMiafkZOxywN4jjUac53v7NI4e1t6eokJXdsoy","paramName":"faculty","docParamName":"education"}
查询后女巫好,我循环:
foreach($params as $k=>$v) {
$paramName = $v->paramName;
$value = $v->value;
$testArr[$v->docParamName] = array();
$testArr[$v->docParamName][$paramName] = $v->value;
}
结果是:
"test":{
"education":
{"high_school":"some High"},
"skills":
{"skill_1":"skill_1 Value"},
"experience":
{"xp_1":"xp1 value"}
}
如果这些参数例如“skill_2”和“skill_3”假设进入“技能”对象,那么事情是我有更多。 但是这个循环得到最后一个参数..
我想在哪里指定一个键或什么东西,以便所有技能都转到技能对象等等。
答案 0 :(得分:1)
你需要这样定义: -
foreach($params as $k=>$v) {
$paramName = $v->paramName;
$value = $v->value;
// $testArr[$v->docParamName] = array(); // comment the line
$testArr[$v->docParamName][$paramName] = $v->value;
}
注意: - 该行已注释,因为您已在$testArr
loop.thanks
foreach
定义为数组
答案 1 :(得分:1)
您在每次迭代时重新初始化您的子对象:
$testArr[$v->docParamName] = array(); // <- By this, you remove all previously
// assigned values
$testArr[$v->docParamName][$paramName] = $v->value;
在向其附加元素之前初始化数组是一个好主意,因为当您尝试追加到非初始化数组时,它会触发警告。但是只应在之前未初始化数组时初始化数组:
if (!array_key_exists($v->docParamName, $testArr)) {
$testArr[$v->docParamName] = array();
}
$testArr[$v->docParamName][$paramName] = $v->value;