简体   繁体   English

根据数组中的值创建数组

[英]Create array from values in an array

This is highly similar to a previous question ( Create an array from multidimensional array ), yet in this case I do not have a multidimensional array. 这与先前的问题( 从多维数组创建数组 )高度相似,但是在这种情况下,我没有多维数组。 Here is what I have: 这是我所拥有的:

Array
(
    [0] => ratings Object
        (
            [id] => 1
            [rating] => 4.4
        )

    [1] => ratings Object
        (
            [id] => 1
            [rating] => 5.0
        )

    [2] => ratings Object
        (
            [id] => 1
            [rating] => 5.0
        )
)

What I'm attempting to do is create a new array that consists of only the "rating" values... 我正在尝试做的是创建一个仅包含“评级”值的新数组...

$result_array = array(0 => "4.4",
                      1 => "5.0",
                      2 => "5.0");

The following solution was unsuccessful since $value is an object rather than an array... 由于$ value是对象而不是数组,因此以下解决方案未成功...

$result_array = array();

foreach ($array as $value) {
    $result_array[] = $value[1];
}

What's the correct way to go about it? 正确的解决方法是什么?

$result_array[] = $value[1];

With the above line, you're trying to use $value as an array when it's not. 在上面的代码行中,您试图在不使用$value时将其用作数组。 It's an object, so treat it as such. 这是一个对象,因此应将其视为。

The properties of an object can be accessed using arrow notation ( -> ). 可以使用箭头符号( -> )访问对象的属性。 The updated code would read: 更新后的代码将显示为:

foreach ($array as $value) {
    $result_array[] = $value->rating;
}

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

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