$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
上面是我的输出,但我想要一个像下面格式的数组。请帮帮我。
正确输出:
$data = array ("id"=>"1","name"=>"mani","lname"=>"ssss");
答案 0 :(得分:1)
选中此项,使用is_numeric来检查号码或字符串。
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
foreach ($data as $key => $val)
{
if(!is_numeric($key))
{
$new_array[$key] = $val;
}
}
print_r($new_array);
输出:
Array
(
[id] => 1
[name] => mani
[lname] => ssss
)
<强> DEMO 强>
答案 1 :(得分:1)
下面的Code-Snippet包含自我解释性评论。它可能会有所帮助:
<?php
// SEEMS LIKE YOU WANT TO REMOVE ITEMS WITH NUMERIC INDEXES...
$data = array( "0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname"=> "ssss"
);
// SO WE CREATE 2 VARIABLES TO HOLD THE RANGE OF INTEGERS
// TO BE USED TO GENERATE A RANGE OF ARRAY OF NUMBERS
$startNum = 0; //<== START-NUMBER FOR OUR RANGE FUNCTION
$endNum = 10; //<== END-NUMBER FOR OUR RANGE FUNCTION
// GENERATE THE RANGE AND ASSIGN IT TO A VARIABLE
$arrNum = range($startNum, $endNum);
// CREATE A NEW ARRAY TO HOLD THE WANTED ARRAY ITEMS
$newData = array();
// LOOP THROUGH THE ARRAY... CHECK WITH EACH ITERATION
// IF THE KEY IS NUMERIC... (COMPARING IT WITH OUR RANGE-GENERATED ARRAY)
foreach($data as $key=>$value){
if(!array_key_exists($key, $arrNum)){
// IF THE KEY IS NOT SOMEHOW PSEUDO-NUMERIC,
// PUSH IT TO THE ARRAY OF WANTED ITEMS... $newData
$newData[$key] = $value;
}
}
// TRY DUMPING THE NEWLY CREATED ARRAY:
var_dump($newData);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
或者甚至简洁地说,你可以这样走过数组:
<?php
$data = array(
"0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname" => "ssss"
);
array_walk($data, function($value, $index) use(&$data) {
if(is_numeric($index)){
unset($data[$index]);
}
});
var_dump($data);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
答案 2 :(得分:0)
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
$new_data = array();
foreach($data as $k => $v)
if(strlen($k)>1) $new_data[$k] = $v;
print_r($new_data);
答案 3 :(得分:0)
我对你究竟想要的东西感到有些困惑。您提供输出示例,但它们看起来像代码。如果您希望输出看起来像代码,那么您需要更清楚。
从长远来看,查看教程和文档对你来说有很多好处。 PHP.net是一个很好的资源,数组文档可以帮助你解决这个问题:http://php.net/manual/en/function.array.php