简体   繁体   English

PHP组合数组键值(在同一数组中)以创建新的键值

[英]PHP Combining array key values (in same array) to create a new key value

Would it be possible to combine an arrays keys to create a new key using the combined key values? 是否可以使用组合键值来组合数组键以创建新键?

I'm not asking to create a function to combine them, just wondering if it is possible to do something like this (obviously this code doesn't work, just showing what I meant in code): 我不是要创建一个将它们组合在一起的函数,只是想知道是否有可能做这样的事情(显然,此代码不起作用,只是显示了我在代码中的含义):

<?php
$box = array(
    "Width" => 10,
    "Height" => 20,
    "Total" => ($box["Width"] + $box["Height"]),
);
echo $box["Total"]; // would show up as 30
?>

No, not while the array is being defined. 不,不是在定义数组时。 array(...) is being evaluated first, the result of which is assigned = to $box . array(...)被首先计算,其结果被指定=$box You can't refer to $box before the evaluation is finished. 评估完成之前,您不能引用$box

You'll have to do it in two steps, or perhaps create a custom class that can do such magic using methods and/or (automagic) getters. 您必须分两步来完成它,或者创建一个可以使用方法和/或(自动)getter进行此类魔术的自定义类。

You need 2 steps: 您需要2个步骤:

$box = array(
    "Width" => 10,
    "Height" => 20,
);
$box["Total"] = $box["Width"] + $box["Height"];
echo $box["Total"];

The easy answer is no. 答案很简单。

To elaborate: this is precisely what classes are meant to do. 详细说明:这正是类要执行的操作。 Note that you can do what you are trying to do very simply: 请注意,您可以非常简单地完成您想做的事情:

<?php
class Box extends ArrayObject
{
  public function offsetGet($key)
  {
    return $key == 'Total' ? $this['Width'] + $this['Height'] : parent::offsetGet($key);
  }
}

$box = new Box(array(
  'Width' => 10,
  'Height' => 20
));

echo $box['Total'],"\n";

Of course $box is not a true array in this example, and as such, cannot directly be used with array functions. 当然, $box在此示例$box不是真正的数组,因此不能直接与数组函数一起使用。 See the docs for ArrayObject . 请参阅ArrayObject的文档。

Since you already have 10 and 20 you can write 由于您已经有10和20,所以可以写

<?php
$box = array(
    "Width" => 10,
    "Height" => 20,
    "Total" => 10 + 30,
);
echo $box["Total"]; // would show up as 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM