简体   繁体   中英

how to get value from array in laravel

In laravel i get this type of array from where query. i want to get only those menu where parent is 0;

 $memus  = Menu::where('parent', 0)->get()->toArray();

 Array
    (
        [0] => Array
            (
                [id] => 13
                [name] => Movies
                [parent] => 0
                [deleted_at] => 
                [created_at] => 2015-04-07 02:48:48
                [updated_at] => 2015-04-07 02:48:48
            )

        [1] => Array
            (
                [id] => 16
                [name] => zxcvxc
                [parent] => 0
                [deleted_at] => 
                [created_at] => 2015-04-07 02:53:26
                [updated_at] => 2015-04-07 03:03:39
            )

        [2] => Array
            (
                [id] => 17
                [name] => alsdkf
                [parent] => 0
                [deleted_at] => 
                [created_at] => 2015-04-07 02:53:41
                [updated_at] => 2015-04-07 03:02:04
            )

    )

So how to get particular value from this array i have tried echo $abc->name and echo $abc->id but not access

You can just do this:

echo $memus[0]['name'];

Or if you want all of them

foreach ($memus as $memu) {
       echo $memu['name'];
}

The arrow ($object->property) notation is for objects.

The notation for accessing array elements is $array[$index][$key] .

So in your case, to access the name key in your second array would be:

echo($menu[1]['name']) , in your example this would echo the string 'zxcvxc'.

You can use collections in laravel 5

collect($arrayName);

$filtered = $arrayName->where('parent', 0);

$filtered->all();

Hope this will help. If not please let me know.

获取特定值

{{memus[0]->id}}

If you want to access some array's data just do $array_name[index]->key in the controller or in the view.

Index is usually an integer and the key is what you are looking to extract. For instance, we would do this on your array: $menu_zero = $menus[0]->id; it would give us 13 and $menu_name_zero = $menu[0]->name; would give the name.

You can do it this way:

For single item you can do this:

echo ($menus[0]['parent'] == 0) ? $menus[0]['name'] : '';

With foreach loop:

 foreach ($menus as $menu) {
        if($menu['parent'] == 0){
            echo $menu['name'];
        }
    }

Use this line for me worked

  $memus  = Menu::where('parent', 0)->get()->toArray();
    $arr = array();
    foreach ($memus as $s) {
        array_push($arr,$s->buy_product_id)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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