dowjgrm6787 2014-12-09 21:10
浏览 48
已采纳

Laravel 4 - 使用php array_push中的id

I am trying to get my query to take the values from my array_push, but can't get it working, unless of course the array is hard coded.

The array comes from a previous query

I'm new to using array_push so would value any input into how best I do this.

$pages = json_encode($pages);
$pages = json_decode($pages, true);

$get_ids = array();
array_push($get_ids, $pages[0]["id"]);

$get_ids = array(10);  // hardcoded 

$getpages = DB::table('pages')
        ->whereIn('id', $get_ids)
        ->select('id', 'title')
        ->get();

array from var_dump gives me

array(1) { [0]=> string(2) "10" } 

JSON from very first query

[{"id":"10","title":"About us"}]
  • 写回答

1条回答 默认 最新

  • doujun1495 2014-12-10 04:07
    关注

    array_push is a built in PHP function to add an element to the end of an array. I think you're looking for array_pluck, which is a Laravel helper function to pluck a specific key from all the items in an array of arrays or array of objects.

    For example:

    $pages = array(
        array('id' => 10, 'name' => 'First'),
        array('id' => 20, 'name' => 'Second')
    );
    
    // get an array of all the page ids
    $ids = array_pluck($pages, 'id'); //= array(10, 20)
    

    array_pluck works with an array of arrays, an array of objects, or even a Laravel Collection (like the results of a database query).

    In the end, your code can probably boil down to something like:

    $get_ids = array_pluck($pages, 'id');
    $getpages = DB::table('pages')
        ->whereIn('id', $get_ids)
        ->select('id', 'title')
        ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧