我试图使用substr提取数组元素值的一部分与if-else语句


I am trying to use substr to extract the part of the array element value with a if-else statement

我是PHP的新手,在如何输出这个方面遇到了一些麻烦。

$employee_numbers = array( "Sam Jerry"=>"1849", "David Flint"=>"2274", "Lena Vincent"=>"2532", Robert Vanny"=>"3471" );

我正在尝试输出它,以便子字符串显示名称和数字。

所以它看起来像这样:

山姆杰瑞的员工编号是: 1849 ——比;管理

你必须遍历数组

$employee_numbers = array( "Sam Jerry"=>"1849", "David Flint"=>"2274", "Lena Vincent"=>"2532", "Robert Vanny"=>"3471" );
foreach($employee_numbers as $employee => $number){
   echo $employee . " employee number is: " .$number . PHP_EOL; //Don't know where the management info is
}

@Marcos是正确的,如果你显示该数组的所有成员。如果你特别想要Sam ,你可以在你的迭代器中抛出一个If子句,或者使用像这样的方法,它可以通过正则表达式直接访问。

无论哪种方式,这里的substr都不是您想要的。这是用来提取部分字符串的:比如从"Sam Jerry"中得到"am Jerry"。

请原谅,我直接从我正在做的一个项目中抄来的

您的用法可能是$result = grep_array('/Sam Jerry/', $employee_numbers);

/**
 * Searches an array for keys that match a rex pattern, and returns those as a new array.
 * example:
 * all global email accounts are stored in the config under the keys
 * 'site.email.$accountid.name', and have a matching 'site.email.$accountid.address'
 * to get an array of [$accountid] => (email, name) :
 *   $grepNames = preg_grep_keys("/site'.email'..*'.name/", $config); will return all the name nodes.
 * walk $grepNames, exploding the keys and pulling [2], which is the $accountid.
 *   preg_grep_keys("/site'.email'.($accountId)'.address/", $config); will match the address node for that accountId
 * the first element of its return will contain the config node.
 *
 * internally, it uses @see preg_grep() for searching.
 *
 * I deprecated calls to get_site_config() in favor the single $config instance when Sarah put it in place
 *
 * @param $pattern string rex pattern to mathch.
 * @param $input array the array to search. generally, this will be the global config.
 * @param int $flags @see preg_grep()
 * @return array elements that match the provided $pattern
 */
function grep_array($pattern, $input = null, $flags = 0)
{
  global $config;
  if ($input === null) {
    $input = $config['fields'];
  }
  return array_intersect_key(
      $input,
      array_flip(preg_grep($pattern, array_keys($input), $flags))
  );
}