I have an array which appears like the one below. I want to slice it in half and create two new arrays from the two halves. However, if I use array_slice, it always returns null… I don’t understand why.
array
'pic' =>
array
0 => string '740' (length=3)
1 => string '741' (length=3)
2 => string '742' (length=3)
3 => string '748' (length=3)
'alt' =>
array
0 => string '' (length=0)
1 => string '' (length=0)
2 => string 'Test caption 1' (length=14)
3 => string 'Test caption 2' (length=14)
The arrays I need should retain the keys, just sliced in half so I have two complimentary halves. For example the first half should look like:
array
'pic' =>
array
0 => string '740' (length=3)
1 => string '741' (length=3)
'alt' =>
array
0 => string '' (length=0)
1 => string '' (length=0)
and the second half:
array
'pic' =>
array
0 => string '742' (length=3)
1 => string '748' (length=3)
'alt' =>
array
0 => string 'Test caption 1' (length=14)
1 => string 'Test caption 2' (length=14)
thanks
ps – to Mike, this is what I’m using to make the array, actually it’s constructed from other arrays itself:
$lodgepics = get_field('accommodation_rooms');
$featuredpics = get_field('featured_pics');
$showcasepics = array();
foreach ($featuredpics as $featuredpic) {
if (isset($featuredpic['featured_pic'])&&!empty($featuredpic['featured_pic'])) $showcasepics[pic][] = $featuredpic['featured_pic'];
if (isset($featuredpic['featured_alt'])) $showcasepics[alt][] = $featuredpic['featured_alt'];
else $showcasepics[alt][] = '';
}
foreach ($lodgepics as $lodgepic) {
if(isset($lodgepic['accommodation_roomphoto'])&&!empty($lodgepic['accommodation_roomphoto'])) $showcasepics[pic][] = $lodgepic['accommodation_roomphoto'];
if(isset($lodgepic['accommodation_roomname'])&&!empty($lodgepic['accommodation_roomname'])) $showcasepics[alt][] = $lodgepic['accommodation_roomname'];
else $showcasepics[alt][] = '';
}
Hard for me to grasp the need to do something like what you are proposing, if it were me I wouldn’t populate an array using your structure, I would create an array like this:
This array structure keeps the image attributes together, rather than keeping them separate.
tomtheman5 has 80% there, but left out the offset, and length params to the array_slice calls that need to be passed to get the correct slices. However he does make a good point, if you stick with your array structure, you may run into issues if you do not have matching elements in each ‘pic’ and ‘alt’ arrays. If this is not a concern, then consider the following snippet:
— Edit —