skip to Main Content
array:5 [
  0 => array:1 [
    "location_id" => 1
  ]
  1 => array:1 [
    "location_id" => 4
  ]
  2 => array:1 [
    "location_id" => 6
  ]
  3 => array:1 [
    "location_id" => 7
  ]
  4 => array:1 [
    "location_id" => 8
  ]
]

convert this into ["1","4","6","7","8",]

as used this ["1","4","6","7","8",]array in different query

4

Answers


  1. You can use the laravel helper array flatten method: Read more about it from here: https://laravel.com/docs/9.x/helpers#method-array-flatten

    // Add the helper class call in the controller header
    use IlluminateSupportArr;
    
    // The actual array
    $array = [
        0 => [
            "location_id" => 1
        ],
        1 =>  [
            "location_id" => 4
        ],
        2 =>  [
            "location_id" => 6
        ],
        3 =>  [
            "location_id" => 7
        ],
        4 =>  [
            "location_id" => 8
        ]
    ];
    
    // Flatten the array function
    $result = Arr::flatten($array);
    

    Results:

    ['1','4','6','7','8']
    
    Login or Signup to reply.
  2. You can use Laravel Collection pluck method to only return property which you want from each array item, and after that flatten the result array with flatten

    $data = [
        [
            "location_id" => 1
        ],
        [
            "location_id" => 4
        ],
        [
            "location_id" => 6
        ],
        [
            "location_id" => 7
        ],
        [
            "location_id" => 8
        ]
    ];
    
    $result = collect($data)->pluck('location_id')->flatten();
    
    Login or Signup to reply.
  3. Not as clean you might want but get the job done:

    $resultSet = collect($data)->map(function($item){
        return $item['location_id'];
    })->toArray();
    
    $resultString = "[";
    foreach($resultSet as $item){
        $resultString .= "'{$item}'" . ",";
    }
    $resultString = rtrim($resultString, ","); // produces this: "['1','4','6','7','8']"
    
    $resultString .= "]";
    
    dd($resultString);
    
    Login or Signup to reply.
  4. You can use the laravel helper array pluck method Read more about it from here: https://laravel.com/docs/9.x/helpers#method-array-pluck

     $array = [
        0 => [
            "location_id" => 1
        ],
        1 =>  [
            "location_id" => 4
        ],
        2 =>  [
            "location_id" => 6
        ],
        3 =>  [
            "location_id" => 7
        ],
        4 =>  [
            "location_id" => 8
        ]
    ];
    $data   = Arr::pluck($array, 'location_id'); // [1,4,6,7,8]
    $result = array_map('strrev', $data); 
    

    Result

    ["1","4","6","7","8"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search