我有一个阵列。我想找到fk_section_id的唯一值以及与之关联的其他字段(section_name& fk_section_id)。我还想通过fk_section_id对这个数组进行排序。如何从原来的阵列中获取这个数组?
阵列
Array
(
[0] => Array
(
[fk_field_id] => 1
[fk_section_id] => 1
[section_order] => 1
[field_order] => 1
[field_name] => Title
[section_name] => Your Detail
[fk_field_type_id] => 4
)
[1] => Array
(
[fk_field_id] => 2
[fk_section_id] => 1
[section_order] => 1
[field_order] => 2
[field_name] => Name
[section_name] => Your Detail
[fk_field_type_id] => 1
)
[2] => Array
(
[fk_field_id] => 3
[fk_section_id] => 2
[section_order] => 2
[field_order] => 1
[field_name] => Road
[section_name] => Address For Correspondence
[fk_field_type_id] => 1
)
)
预期产出
Array
(
[0] => Array
(
[fk_section_id] => 1
[section_order] => 1
[section_name] => Your Detail
)
[1] => Array
(
[fk_section_id] => 2
[section_order] => 2
[section_name] => Address For Correspondence
)
)
我在下面试过
$i=0;
foreach($formFields as $val){
$i++;
$allSections[$i]['section_name'] = $val['section_name'];
$allSections[$i]['fk_section_id'] = $val['fk_section_id'];
$allSections[$i]['section_order'] = $val['section_order'];
}
它给出了
Array
(
[0] => Array
(
[section_name] => Your Detail
[fk_section_id] => 1
[section_order] => 1
)
[1] => Array
(
[section_name] => Your Detail
[fk_section_id] => 1
[section_order] => 1
)
[2] => Array
(
[section_name] => Address For Correspondence
[fk_section_id] => 2
[section_order] => 2
)
)
答案 0 :(得分:1)
你可以试试这个:
$data = array(
array(
'fk_field_id' => 1,
'fk_section_id' => 1,
'section_order' => 1,
'field_order' => 1,
'field_name' => 'Title',
'section_name' => 'Your Detail',
'fk_field_type_id' => 4,
),
array(
'fk_field_id' => 2,
'fk_section_id' => 1,
'section_order' => 1,
'field_order' => 2,
'field_name' => 'Name',
'section_name' => 'Your Detail',
'fk_field_type_id' => 1,
),
);
$temp = array();
foreach($data as $key => $value) { //Make an new array using fk_field_id as key
if (!in_array($value['fk_field_id'], $temp)) {
$temp[$value['fk_field_id']] = $value;
}
}
ksort($temp); //Sort the array by key
var_dump($temp);
结果:
array (size=2)
1 =>
array (size=7)
'fk_field_id' => int 1
'fk_section_id' => int 1
'section_order' => int 1
'field_order' => int 1
'field_name' => string 'Title' (length=5)
'section_name' => string 'Your Detail' (length=11)
'fk_field_type_id' => int 4
2 =>
array (size=7)
'fk_field_id' => int 2
'fk_section_id' => int 1
'section_order' => int 1
'field_order' => int 2
'field_name' => string 'Name' (length=4)
'section_name' => string 'Your Detail' (length=11)
'fk_field_type_id' => int 1
现在您也可以使用:
echo $temp[1]['field_name'];
结果:
Title