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".
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.
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.
So this will work:
if(array_search($gid, $result['canv']) !== false){
//Do Stuff
}
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. 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.
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.
精彩评论