0
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",]

So that I can use this array (["1","4","6","7","8",]) in different query.

0

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Absolutely, I assumed his array was static as it is, forgot that it might include other data as well.
0

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 Illuminate\Support\Arr;

// 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']

2 Comments

i have that type of answer but I need to use that array in laravel "WHEREIN" condition so need array like this ["1","4","6","7","8",].
@kinjalparmar that is exactly what flatten does, it gives you an array ['1','4','6','7','8'] if you are having a problem with using it in your query, its best if you post the actual problem.
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.