Reference key from same array

你。 提交于 2019-12-21 05:21:52

问题


I'm trying to reference the key/value pair of an item in the same array:

$glossary_args = array(
    'name'          => 'Glossary Terms',
    'singular_name' => 'Glossary Term',
    'add_new'       => 'Add New Term',
    'edit_item'     => 'Edit Term',
    'search_items'  => 'Search'.$glossary_args["name"],
)

Is this even possible? If so, how?


回答1:


You can use the fact that assignment is itself an expression in PHP:

$glossary_args = array(
    'name'          => ($name = 'Glossary Terms'),
    'singular_name' => 'Glossary Term',
    'add_new'       => 'Add New Term',
    'edit_item'     => 'Edit Term',
    'search_items'  => 'Search'.$name
)



回答2:


You can't do this when you're first defining the array - while you're inside array(), $glossary_args hasn't been created yet. Try this:

$glossary_args = array(
  'name' => 'Glossary Terms',
  'singular_name' => 'Glossary Term',
  'add_new' => 'Add New Term',
  'edit_item' => 'Edit Term'
);
// first we create the rest of $glossary_args, then we set search_items
$glossary_args['search_items'] = 'Search '.$glossary_args["name"];


来源:https://stackoverflow.com/questions/12185545/reference-key-from-same-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!