2

Is it possible to explode an array like this.

$arr=array();
$arr[0]['id']='123';
$arr[0]['otherdatas']=
$arr[1]['id']='234';
$arr[1]['otherdatas']=
$arr[2]['id']='567';
echo "string: ".explode($arr[]['id'],',');

and end up with this?

string: 123,234,567

Doing the above results in:

Fatal error: Cannot use [] for reading in /data/www/test.php on line 8

How can I go about this without doing something like...

function getIDs(){
    foreach($arr as $val){
        if($string){$string.=',';}
        $string.=$arr['id'];
    }
    return $string;
}

Is there some better way to go about this?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Steve Payne
  • 612
  • 3
  • 8
  • 16

3 Answers3

7

First of all, you're trying to implode the strings, not explode. Secondly, no, there's no syntax shortcut for expressing the operation "join all id keys in all sub arrays together". You can do it very concisely like this though:

echo join(',', array_map(function ($i) { return $i['id']; }, $arr));
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Concise. @Steve, do keep in mind that anonymous functions, such as in this example, only work in PHP 5.3+ – Nadh May 01 '12 at 06:10
  • For PHP 5.2-: `join(',', array_map(create_function('$i', 'return $i["id"];'), $arr))`. – deceze May 01 '12 at 06:19
2

From PHP5.5 and up, you can call array_column() to isolate a single column of data in your multi-dimensional array.

Code: (Demo)

$arr=array();
$arr[0]['id']='123';
$arr[0]['otherdatas']='';
$arr[1]['id']='234';
$arr[1]['otherdatas']='';
$arr[2]['id']='567';

echo implode(',',array_column($arr,'id'));

Output:

123,234,567
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

no, it`s impossible.

function myExplode ($data=array(),$row='id',$delimiter=','){
  $result='';
  foreach ($data as $item) $result.=($data[$row])?$delimiter.$data[$row]:'';
  return $result;
}
sl4mmer
  • 381
  • 1
  • 13