以下代码有效。我有以下数组,我想用array_column搜索并在(n)列返回相应的值。目前,我的代码只返回右侧的列或左侧的列。
现有工作代码
function getField_UnitPrice($xmc) {
// Key values MUST ALWAYS BE UNIQUE.
// Values on the left.
$xmpd_db = array(
1 => array('EA_WTRESRVD', '122.67'),
2 => array('EA_WTRESRV', '184.00'),
3 => array('EA_FEEASBT', '300.00'),
4 => array('GL_WTREXTWP', '0.64'),
5 => array('GL_WTREXTWPA', '0.96')
);
$search_result = array_column($xmpd_db, 1, 0);
return $search_result[$xmc];
}
正如您所看到的,此函数返回您查找的代码的价格,但如果数组数组的列数超过2列会怎样?
我认为答案在于下面的代码行,但无论我如何更改这些索引只不过代码列显示..
$search_result = array_column($xmpd_db, 1, 0);
目标
function getField_Target($xmc, $column_index)
{
// Key values MUST ALWAYS BE UNIQUE.
// Values on the left.
$xmpd_db = array(
1 => array('EA', 'WTRESRVD', 'EMERGENCY SERVICE CALL', '122.67'),
2 => array('EA', 'WTRESRV', 'EMERGENCY SERVICE CALL AFTER HOURS', '184.00')
);
$search_result = array_column($xmpd_db, 0, 1);
return $search_result[$xmc];
}
解决方案
/* $field, 1, 0 = EA */
$unit_of_measure = getField_Target($field, 1, 0);
/* $field, 1, 1 = WTRESRVD*/
$code = getField_Target($field, 1, 1);
/* $field, 1, 2 = EMERGENCY SERVICE CALL*/
$code_desc = getField_Target($field, 1, 2);
/* $field, 1, 3 = 000.00*/
$code_price = getField_Target($field, 1, 3);
// Call
echo $unit_of_measure . " - " . $code . " - " . $code_desc . " - " . $code_price . "<br>";
function getField_Target($xmc, $column_index = 1, $column_value = 3) {
// Key values MUST ALWAYS BE UNIQUE.
// Values on the left.
$xmpd_db = array(
1 => array('EA', 'EA_WTRESRVD', 'EMERGENCY SERVICE CALL', '000.10'),
2 => array('EA', 'EA_WTRESRV', 'EMERGENCY SERVICE CALL AFTER HOURS', '000.20')
);
$search_result = array_column($xmpd_db, $column_value, $column_index);
return $search_result[$xmc];
}
答案 0 :(得分:1)
您需要的是......
$search_result = array_column($xmpd_db, 3, 1);
这样做是取第3个(实际上是第4个,因为它是零基础)字段(价格字段)并将其索引到第1个(即第2个)列。
所以$search_result
最终为
Array
(
[WTRESRVD] => 122.67
[WTRESRV] => 184.00
)
扩展代码...
function getField_Target($xmc, $column_index = 1, $column_value = 3)
{
// Key values MUST ALWAYS BE UNIQUE.
// Values on the left.
$xmpd_db = array(
1 => array('EA', 'WTRESRVD', 'EMERGENCY SERVICE CALL', '122.67'),
2 => array('EA', 'WTRESRV', 'EMERGENCY SERVICE CALL AFTER HOURS', '184.00')
);
$search_result = array_column($xmpd_db, $column_value, $column_index);
return $search_result[$xmc];
}
所以,
echo getField_Target('WTRESRV'); // 184.00
echo getField_Target('WTRESRV', 1, 2); // EMERGENCY SERVICE CALL AFTER HOURS