【问题标题】:How to push key/value pair to array as separated element if key is already there?如果键已经存在,如何将键/值对作为分隔元素推送到数组?
【发布时间】:2018-03-16 23:07:35
【问题描述】:

这就是easticsearch查询逻辑的全部内容......我需要使用这样的数组发送查询:

`"query" => array:2 [▼
    "match" => array:2 [▼
      "location" => array:2 [▼
        "query" => "USA"
      ],
    "match" => array:2 [▼
      "car" => array:2 [▼
        "query" => "FORD"          ]
    ]
  ]`

当我们尝试生成具有相同键的数组时,问题就开始了:

   $rules['query'] = [];
   foreach ($field_value_array as $key => $value) {   
                    $match['match'][$key] = [
                      'query' => $value ]; 
                    $rules['query'] =  $match;
            }

PHP 会自动删除它们,只留下最后一个。 array_push 函数在这种情况下不起作用。

你是我最后的希望。

【问题讨论】:

  • "match" 数组中不能有两个 "match" 键。你的意思是:"query"=>[0=>['match'=>[...]],1=>['match'=>[...]]
  • 系统调用是正确的。您不能有重复的密钥。请参阅this 答案。

标签: php arrays loops multidimensional-array foreach


【解决方案1】:

"query" 数组中不能有两个 "match" 键。

那么,你缺少[]$rules['query'] = $match;,所以最后一个值会覆盖前一个值,你只会得到最后一个。

最后,使用['query' => $value ],你会得到一个额外的“索引”,你可以使用$match['match'][$key]['query'] = $value;

你可以试试这样的:

$field_value_array=['location' => 'USA','cars' => 'FORD'];
$rules['query'] = [];
foreach ($field_value_array as $key => $value) {
    $match=[]; // reset $match to avoid duplicate keys
    $match['match'][$key]['query'] = $value;
    $rules['query'][] =  $match;
}
print_r($rules);

将输出:

Array (
    [query] => Array (
            [0] => Array (
                    [match] => Array (
                            [location] => Array (
                                    [query] => USA
                                )
                        )
                )
            [1] => Array (
                    [match] => Array (
                            [cars] => Array (
                                    [query] => FORD
                                )
                        )
                )
        )
)

【讨论】:

  • 非常感谢!但最大的挑战是弹性服务器只接受提到的结构。我猜他们正在考虑他们的 API 的 js 实现,但使用 json 对象也是不可能的......如果 Ill write this array manually it works: ['match' => ['location' => ['query' => 'USA']], 'match' => [ 'car' => ['query' => 'AUDI']],] ` 但我想用foreach 生成这样的数组是不可能的:( 最糟糕的变种是使用switch 但是这不是很好的做法......
  • @VladislavPanin 感谢您的回复。有趣的。我认为使用 PHP 编写这样的数组是不可能的。 $data=['query'=>['match'=>['test'],'match'=>['test2']]]; print_r($data); 将只输出一个 match 键。你是怎么写的?
  • 我只是按原样发送了它...无论如何,我找到了使多个字段过滤器工作的方法。但这对我来说仍然是神秘的事情。即使print_r 合并这个数组并且只给出一个唯一键。因此,他们如何读取该数组仍然是一个悬而未决的问题。我认为最好的方法是编写它们并询问那里的开发人员......这非常有趣:)
猜你喜欢
  • 2019-05-04
  • 2019-01-21
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
  • 2017-07-28
  • 2022-01-23
相关资源
最近更新 更多