0

I have an array of date like this

Array ( [0] => Array ( [imageName] => WNgrRdqZ [alt] => alt text ) [1] => Array ( [imageName] => xoPS0udB [alt] => Alt ) ) 

And I'm wanted to format it so I get one array of imageNames, and one array of alt. I can do this simply with a foreach loop, but I'm curious if there's a build in PHP function I could use instead of rewriting something else. I've not found anything useful yet in the PHP manual.

EDIT: It could also be split into 1 array with 2 sub arrays, e.g.

Array ( ['imageName'] => Array(..), ['alt'] => Array(...) ) 
4
  • 3
    from the manual: array_column Commented Jul 9, 2014 at 10:14
  • How did I miss that! Thank you :). If you post that as an answer I'll accept it for you. Commented Jul 9, 2014 at 10:16
  • Just take Sudecs answer ;) Commented Jul 9, 2014 at 10:19
  • Will do :P when SO let's me! Commented Jul 9, 2014 at 10:19

3 Answers 3

3

You can use array_column():

$imageName = array_column($Array, 'imageName'); $alt = array_column($Array, 'alt'); 
Sign up to request clarification or add additional context in comments.

3 Comments

he want the output array like this Array ( [imagename] => Array ( [0] => WNgrRdqZ [1] => xoPS0udB ) [alt] => Array ( [0] => alt text [1] => Alt ) )
I see no problem there. Just put the 2 resulting arrays into one after splitting the collumns
array_column is not supported in early version of php
0

You can use array_reduce:

<?php $data = array ( array ( 'imageName' => 'WNgrRdqZ', 'alt' => 'alt text' ), array ( 'imageName' => 'xoPS0udB', 'alt' => 'Alt' ) ); $reduced = array_reduce($data,function($carry, $item){ $carry['imageName'][] = $item['imageName']; $carry['alt'][] = $item['alt']; return $carry; },array()); print_r($reduced); 

Working example https://ideone.com/48JXvL

Comments

0

please review this code

<?php $arraystest = array(0 => array('imageName' => 'WNgrRdqZ', 'alt' => 'alt text'), 1 => array('imageName' => 'xoPS0udB', 'alt' => 'Alt')); $i = 0; $newarray = array(); foreach ($arraystest as $item) { $newarray['imagename'][$i] = $item['imageName']; $newarray['alt'][$i] = $item['alt']; $i++; } print_r($newarray); exit; ?> 

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.