Get first value of an array [duplicate]

依然范特西╮ 提交于 2020-07-03 04:34:46

问题


I have an array:

Array (
[0] => Array
    (
        [0] => Pen
        [1] => Apple
    )

[1] => Array
    (
        [0] => Oooo
        [1] => Pineapple pen
    )

How I can get a first elements of each array?

For example: Pen Oooo

It's my function

$parameters = array('wiki_1', 'wiki_2', 'wiki_3', 'wiki_4','wiki_5' ,'wiki_6', 'wiki_7', 'wiki_8', 'wiki_9', 'wiki_10', 'wiki_11', 'wiki_12');

function wiki_custom_fields( $parameters, $id ) {
        foreach ($parameters as $parameter) {
           $wiki_result[] = get_post_custom_values($parameter, $id, true);
        }

    echo '<pre>';
    print_r($wiki_result);
    echo '</pre>';
}

If I use print_r($wiki_result[][0]); it's get 500 Error.


回答1:


You can use array_column function

$array =  array(
    array('Pen', 'Apple' ),
    array('Oooo', 'Pineapple pen')
);

$result = array_column($array, 0);

echo '<pre>';
print_r($result);
echo '</pre>';

Output:

Array
(
    [0] => Pen
    [1] => Oooo
)



回答2:


Use reset http://php.net/manual/es/function.reset.php

This function sets the internal pointer of the array to first element and also returns it.

$first = reset($array)




回答3:


$param = array('first_key'=> 'First', 2, 3, 4, 5);
$keys   =   array_keys($param);
echo "Key = ".$keys[0];

example:

    $parameters = array('wiki_1', 'wiki_2', 'wiki_3', 'wiki_4','wiki_5' ,'wiki_6', 'wiki_7', 'wiki_8', 'wiki_9', 'wiki_10', 'wiki_11', 'wiki_12');

function wiki_custom_fields( $parameters, $id ) {
        foreach ($parameters as $parameter) {
           $wiki_result[] = get_post_custom_values($parameter, $id, true);
        }

    $keys   =  array_keys($wiki_resul);
    echo "Key = ".$keys[0];
    echo '<pre>';
    print_r("Key = ".$keys[0]);
    echo '</pre>';
}



回答4:


Try:

$result = array();
foreach ($elements as $elem){
    $result[] = $elem[0];
}

$result contains 'Pen', 'Oooo'.

The sintaxis $result[] is for adding a element to the last position in the array, the same as array_push (http://php.net/manual/es/function.array-push.php)




回答5:


try this code

print_r($wiki_result[0]);


来源:https://stackoverflow.com/questions/40192716/get-first-value-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!