简体   繁体   English

php数组重建

[英]Php array rebuild

I got an array looking like this: 我得到一个看起来像这样的数组:

array("canv" => array(1 => "4", 2 => "6", 3 => "9", 4 => "7");

I need it to look like this: 我需要它看起来像这样:

array("canv" => array("4", "6", "9", "7");

so I can easly check if the value exist this way: 所以我可以轻松地检查值是否以这种方式存在:

if(isset($result["canv"][$gid])) where $gid is a number from "4", "6", "9", "7". if(isset($result["canv"][$gid]))其中$ gid是“ 4”,“ 6”,“ 9”,“ 7”中的数字。

How can it be done? 如何做呢?

This will flip the values to become keys and vice versa: 这将翻转值成为键,反之亦然:

$result["canv"] = array_flip($result["canv"]);

So instead of 所以代替

array(1 => "4", 2 => "6", 3 => "9", 4 => "7")

you'll have 你会有

array("4" => 1, "6" => 2, "9" => 3, "7" => 4)

But then again think about building the original array in the desired way and only do this if you can't afford that. 但是,再考虑以所需的方式构建原始数组,只有在您负担不起的情况下才这样做。

Without any modification, with your existing array, you can check it as: 在不做任何修改的情况下,使用现有阵列,您可以将其检查为:

if (in_array($gid, $result["canv"])) {
  // $gid is in the array
}

Logically, if canv is to be an array of those values, the values should be array members rather than the array keys which point to members. 从逻辑上讲,如果canv是这些值的数组,则这些值应该是数组成员,而不是指向成员的数组键。 You are asking to use them as array keys. 您要使用它们作为数组键。 Unless you want them to behave as keys later on, whereby they will be used to point to array values, you should not change them now. 除非您希望它们以后充当键,否则它们将用于指向数组值,否则您现在不要更改它们。

It won't work because you are looking for array keys, while 4, 6, 9 and 7 are the values, but if you use array_search($gid, $result['canv']) you'll find the index of $gid or false if $gid 's value is not in the list. 因为您正在寻找数组键,而array_search($gid, $result['canv'])和7是值,所以它array_search($gid, $result['canv']) ,但是如果您使用array_search($gid, $result['canv'])您会发现$gid的索引如果$gid的值不在列表中, $gid $gidfalse

So this will work: 所以这将工作:

if(array_search($gid, $result['canv']) !== false){
    //Do Stuff
}

Then I don't think you want it to look like that.... You want it to look like this: 然后,我认为您不希望它看起来像这样。...您希望它看起来像这样:

array( 
    "canv" => array( 
        4 => "value", 
        6 => "value", 
        9 => "value", 
        7 => "value" 
    )
)

You did not specify what values you want, but it may not matter. 您没有指定所需的值,但这可能无关紧要。 You can arrive at at that however you want, but if you wind up with an array with (4,6,9,7) in it, you can just do array_flip and it will exchange the keys with the values. 您可以根据需要达到此目的,但是如果最终得到一个包含(4,6,9,7)的数组,则可以执行array_flip ,它将与值交换键。

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

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