如果来自数组,则显示来自数组的值

时间:2019-04-30 12:41:12

标签: php arrays

对不起,我不喜欢php,我在查找数组中的内容时遇到了一些问题,如果它的建立显示了该数组的完整行。

可能很简单,但我找不到解决方法

代码必须与php 5.2兼容

if (isset($_POST)) {

    $companies = [
        ['label' => 'Sandwich', 'campaign' => 12, 'variant' => '1a'],
        ['label' => 'Burgers', 'campaign' => 13, 'variant' => '1b'],
        ['label' => 'Bread', 'campaign' => 14, 'variant' => '1c'],
        ['label' => 'Coke', 'campaign' => 15, 'variant' => '1d'],
        ['label' => 'Pepsi', 'campaign' => 16, 'variant' => '1e'],
        ['label' => 'Fanta', 'campaign' => 17, 'variant' => '1f'],
        ['label' => 'Pepper', 'campaign' => 18, 'variant' => '1g']

    ];

    $code = $_POST['code'];
    $codeST = strtoupper($code);
    $ar = array_column($companies, 'label');

    if (in_array($codeST, $ar)) {
        $campaign = "Campaign value for founded label";
        $variant = "Variant value for founded label";
        echo json_encode('{"status":"Ok","label": "' . $code . '", "campaign": "' . $campaign . '", "variant": "' . $variant . '"}');

    } else {
        echo json_encode('{"status":"No"}');
    }
}

如果标签与发布的值相同,则需要广告系列和变体的显示值

2 个答案:

答案 0 :(得分:0)

使用array_search来获取对应于该值的键(如果确实存在),而不是使用in_array来返回正确/错误的结果。然后,您可以将其用作索引来获取campaignvariant的值。

$code = $_POST['code'];
$codeST = ucfirst(strtolower($code));
$ar = array_column($companies, 'label');
if (($key = array_search($codeST, $ar)) !== false) {
    $campaign = $companies[$key]['campaign'];
    $variant = $companies[$key]['variant'];
    echo '{"status":"Ok","label": "' . $codeST . '", "campaign": "' . $campaign . '", "variant": "' . $variant . '"}';

} else {
    echo '{"status":"No"}';
}

注释:

  1. array_search如果找不到值,则返回false
  2. 您的字符串已经是JSON,您不需要 json_encode也是如此。我已经删除了这些电话...
  3. 根据$companies数组中的标签,您应该使用ucfirst(strtolower($code)),而不是strtoupper($code)

如果为$_POST['code'] = 'BReAd',则此代码将输出:

{"status":"Ok","label": "Bread", "campaign": "14", "variant": "1c"}

Demo on 3v4l.org

答案 1 :(得分:0)

您需要遍历$ companies来匹配标签,然后访问相关数据,这是解决方案。     如果(isset($ _ POST)){

  $companies = [
    ['label' => 'Sandwich', 'campaign' => 12, 'variant' => '1a'],
    ['label' => 'Burgers', 'campaign' => 13, 'variant' => '1b'],
    ['label' => 'Bread', 'campaign' => 14, 'variant' => '1c'],
    ['label' => 'Coke', 'campaign' => 15, 'variant' => '1d'],
    ['label' => 'Pepsi', 'campaign' => 16, 'variant' => '1e'],
    ['label' => 'Fanta', 'campaign' => 17, 'variant' => '1f'],
    ['label' => 'Pepper', 'campaign' => 18, 'variant' => '1g']

  ];

  $code = $_POST['code'];
  $codeST = strtoupper($code);
  foreach ($companies as $company){
    if($company['label']==$codeST){
      $campaign = $company['campaign'];
      $variant = $company['variant'];
      echo json_encode('{"status":"Ok","label": "' . $code . '", "campaign": "' . $campaign . '", "variant": "' . $variant . '"}');
    } else {
      echo json_encode('{"status":"No"}');
    }
  }
}