Search code examples
phplaravellaravel-4array-push

Laravel 4 - using id's from php array_push


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"}]

Solution

  • 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();