我有像这样的数组数据
@app.route('/newcontrolaccount', methods=['POST', 'GET'])
def newcontrolaccount():
form = ControlAccountForm()
if request.method == "POST" and form.validate():
#accounttype = form.accounttype.data
controlaccount = ControlAccount (code= form.code.data,
name= form.name.data,
#accounttype = form.accounttype.data,
budget = form.budget.data,
PMB_start = form.PMB_start.data,
PMB_finish = form.PMB_finish.data,
PMU_start = form.PMU_start.data,
PMU_finish = form.PMU_finish.data,
parent_id = form.parent_id.data,
#curve_id = form.curve_id.data,
project = form.project_id.data
)
db.session.add(controlaccount)
db.session.commit()
return redirect(url_for('ca_added'))
return render_template('controlaccounts/newaccount.html', form=form, action='new')
所以我想将每个 Array(
[0] => stdClass Object
([iditem] => 31702152
[idcolor] => 39 )
[1] => stdClass Object
([iditem] => 31702152
[idcolor] => 38))
添加到新变量idcolor
,结果为$colorid
。
我找不到匹配关键字,或者我可以获得类似问题的链接吗?
答案 0 :(得分:1)
您可以使用array_map映射/返回新数组,因为它是针对此类工作设计的,假设为:
// creating array of object
$a = (object) array('iditem' => 31702151,'idcolor' => 38 );
$b = (object) array('iditem' => 31702152,'idcolor' => 39 );
// placing above data to new array container
$ab = array($a,$b);
// callback function
function getData( $obj ) {
return $obj->idcolor;
}
// array_map the array using above callback
$colorid = array_map("getData", $ab );
print_r( $colorid );
以上代码将生成Array( [0] => 39, [1] => 38 )
。如果您希望将值直接存储在变量中作为单个字符串用逗号分隔,只需使用 implode 函数执行此操作:
$newStr = implode(',', $colorid );
// which will produce 38,39
答案 1 :(得分:0)
如果我理解正确的话,你希望$colorid
成为一个包含所有id的数组吗?
$colorid = array();
foreach($array as $object)
array_push($colorid, $object->idcolor);
答案 2 :(得分:0)
$ids = [];
foreach($youarray as $value) {
$ids[] = $value->idcolor;
}
$finalIds = implode(',', $ids);
$finalIds = '';
foreach($youarray as $value) {
$finalIds = $value->idcolor.',';
}
$finalIds = rtrim($finalIds, ',');
答案 3 :(得分:0)
您可以使用array_reduce来完成工作:
<?php
// your data
$data = array(
(object) array('iditem' => 31702152, 'idcolor' => 39),
(object) array('iditem' => 31702152, 'idcolor' => 38),
);
// the code
$output = array_reduce($data, function($carry, $obj) {
if (isset($obj->idcolor)) $carry[] = $obj->idcolor;
return $carry;
}, array());
sort($output); // directly sort the $output variable
$output
将是:
array(38, 39);