简体   繁体   English

卡在array_merge中,需要在foreach循环内进行特定的键值安排

[英]stuck with array_merge, need specific key value arrangement inside foreach loop

I've following PHP code: 我正在遵循PHP代码:

$age = array_merge($age,array(get_user_meta($comment->user_id, 'wsl_user_age', true)));

This produces: 这将产生:

Array
(
    [0] => 26
    [1] => 
    [2] => 18
    [3] => 28
    [4] => 22
    [5] => 21
    [6] => 26
    [7] => 
    [8] => 
    [9] => 
    [10] => 
    [11] => 
    [12] =>
    [13] =>
    [14] =>
    [15] =>
    [16] =>
    [17] =>
    [18] =>
    [19] =>
    [20] =>
)

What I'd like to have is 26 18 etc as keys. 我想要的是26 18等作为键。 And values number of times it repeats, in essence duplicate count. 并且重视重复的次数,实质上是重复计数。

I tried: 我试过了:

$age = array_merge($age,array(get_user_meta($comment->user_id, 'wsl_user_age', true)=> ""))

But this produced absolute nonsense. 但是,这绝对是胡说八道。

What should I try? 我该怎么办?

I think you are looking for array_count_values 我认为您正在寻找array_count_values

$cnt_array = array_count_values($your_array);

echo "<pre>";
print_r($cnt_array);

Ref: http://www.php.net/manual/en/function.array-count-values.php 参考: http : //www.php.net/manual/en/function.array-count-values.php

Here is something you might be looking for http://codepad.org/RDUhltQ7 您可能正在这里寻找http://codepad.org/RDUhltQ7

have a look 看一看

$foo = Array
(   26,
    18,
    28,
    22,
    21,
    26,
    '',
    ''
);

$foo = array_filter($foo);
$foo = array_count_values($foo);

print_r($foo);

http://sandbox.onlinephpfunctions.com/code/a1875256f4680b06b9d909bdb3329cfcd64d44de http://sandbox.onlinephpfunctions.com/code/a1875256f4680b06b9d909bdb3329cfcd64d44de

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM