我试图使用substr用if-else语句

时间:2015-09-30 02:51:45

标签: php if-statement substr

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

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

我正在尝试输出它,以便substr显示Name和number。

所以它看起来像这样

Sam Jerry 员工编号为: 1849 - >管理

先谢谢

2 个答案:

答案 0 :(得分:1)

你必须循环遍历数组。

$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
}

答案 1 :(得分:0)

如果您正在显示该阵列的所有成员,那么@Marcos是正确的。如果你想要Sam 特别是,你可以在你的迭代器中抛出一个if子句,或者使用类似这种方法的东西,通过grepping来通过正则表达式直接访问一些伏都教。

无论哪种方式,substr都不是你想要的。这是为了取出部分字符串:比如得到"是Jer"来自" Sam 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))
  );
}