how can i return an array
how can i return an array like :
$array = array(
1 => array('id' => '12开发者_如何学JAVA','name' => 'Great man'),
2 => array('id' => '14','name' => 'Lamborgini'),
3 => array('id' => '29','name' => 'Leon'),
);
please attention to first keys
Just return $array, it already holds the right values. There's nothing in PHP stopping you from returning data of any type you want.
you can use arrays in php like any other variable:
function return_an_array() {
return array(
1 => array('id' => '12','name' => 'Great man'),
2 => array('id' => '14','name' => 'Lamborgini'),
3 => array('id' => '29','name' => 'Leon'),
);
}
$my_array = return_an_array();
you can use $array like any PHP var.
e.g.:
foreach($array as $value)
{
// now use $value['id'] or $value['name'];
// sample:
echo 'ID: '.$value['id'].'<br/>';
echo 'NAME: '.$value['name'].'<br/>';
}
and
$great_man = $array[1];
echo 'id: '.$great_man['id'].' name: '.$great_man['name'];
When you say return an array, I think you might mean access an array?
$array = array(
1 => array('id' => '12','name' => 'Great man'),
2 => array('id' => '14','name' => 'Lamborgini'),
3 => array('id' => '29','name' => 'Leon'),
);
echo $array[1]['id']; // 12
echo $array[1]['name']; // Great Man
echo $array[3]['name']; // Leon
I think what the OP is wanting, is to use the id of each element as the key. A simple enough thing to achieve.
So, instead of your original code of:
$array = array(
1 => array('id' => '12','name' => 'Great man'),
2 => array('id' => '14','name' => 'Lamborgini'),
3 => array('id' => '29','name' => 'Leon'),
);
You would simply use:
$array = array(
12 => 'Great man' ,
14 => 'Lamborgini' ,
29 => 'Leon'
);
NOTE: The Array Keys do not have to be sequential, but they do need to be unique, within that array. They can also be either integers or strings.
精彩评论