gpt4 book ai didi

php - 通过参数传递对象的键

转载 作者:可可西里 更新时间:2023-10-31 23:23:06 25 4
gpt4 key购买 nike

我有这个代码:

function cmp_asc($a, $b){
$ta = date_create_from_format('Y/m/d', $a['props']['t']); // Y/n/j si no tienen 0 inicial
$tb = date_create_from_format('Y/m/d', $b['props']['t']);
$interval = date_diff($ta, $tb);

if($interval->days != 0){
if($interval->invert == 1){
return 1;
}else{
return -1;
}
}else{
return 0;
}
}

$arr1 = array(
'props' => array('t' => '2012/05/20')
);

$arr2 = array(
'props' => array('t' => '2012/05/21')
);

$arr3 = array(
'props' => array('t' => '2012/04/14')
);

$arr = array($arr1, $arr2, $arr3);

uasort($arr, 'cmp_asc');

我想知道我是否可以通过参数传递 ['props']['t']。所以,它最终会像这样:

function cmp_asc($a, $b, $key){
$ta = date_create_from_format('Y/m/d', $a <-- $key -->);
...
...

我正在考虑可变变量,但我不太确定这是正确的方法。还有其他想法吗?

最佳答案

不是真正的参数,因为你不是自己调用函数,但你可以使用 closures将其他变量传递给函数:

$key1 = 'props';
$key2 = 't';

uasort($arr, function ($a, $b) use ($key1, $key2) {
$ta = date_create_from_format('Y/m/d', $a[$key1][$key2]);
...
});

这只是一个简单的例子。如果您需要动态键深度,则需要更多代码,如下所示:

function getValue(array $value, $key) {
$keys = explode('.', $key);
foreach ($keys as $k) {
$value = $value[$k];
}
return $value;
}

$arr = array('foo' => array('bar' => 'baz'));
echo getValue($arr, 'foo.bar');

另一个想法是使用类,其用法如下所示:

$cmp = new ComparisonClass;
$cmp->key = 'props.t';

uasort($arr, array($cmp, 'compare'));

我会让你弄清楚 ComparisonClass 的实现。

更好的解决方案可能是简单地标准化您要排序的数组的格式。

关于php - 通过参数传递对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11985569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com