Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am getting array like this:

[0] => Array
    (
        [id] => 1
        [name] => Earl E
    )

[1] => Array
    (
        [id] => 2
        [name] => Juan Morefore DeRhode
    )

[2] => Array
    (
        [id] => 36
        [name] => Mack Truck
    )

[3] => Array
    (
        [id] => 37
        [name] => Phil Addio
    )

My Loop looks like this:

$name_arr_val = array();
for($i=0; $i<count($name); $i++){
    $name_arr_val[] = str_replace(',', '', $name[$i]['name']);
}
echo $name_list = '"' . implode('", "', $name_arr_val) . '"'; 

How to genrate out like bellow:

['1', 'Earl E'],
['2', 'Juan Morefore DeRhode'],
['36', 'Mack Truck'],
['37', 'Phil Addio']

Any ideas or suggestions? Thanks.

share|improve this question
    
do you need just an output or a new array with exact indices? –  vladkras Sep 6 '13 at 9:11
    
If you're generating JSON, take a look at json_encode. All you have to do is create an array in the right format (which involves simply turning array('id' => $id, 'name' => $name) into array($id, $name)). –  cHao Sep 6 '13 at 9:12
add comment

4 Answers

up vote 1 down vote accepted

Maybe something like this:

$output = array();

foreach ( $array as $item ) {
    $id = $item['id'];
    $name = $item['name'];

    // single quotes
    $output[] = "['$id', '$name']";        
    // double quotes
    $output[] = '["' . $id . '", "' . $name . '"]';  
}

echo implode( ",\n", $output );

But maybe what you are looking for is a JSON?

echo json_encode( $array );
share|improve this answer
    
I want to use in double quotation marks. can you help me. –  Manan Sep 6 '13 at 9:11
add comment

try this

   $print="";
   foreach($arrayname as $arr){
     $print.='['.$arr['id'].','.' '.$arr['name'].']'.'<br>'
    }echo $print;
share|improve this answer
add comment

can you please used this :

$output = array();
foreach ( $array as $item ) { 
    $output[] = "['".$item['id']."', '".$item['name']."']";        
}
echo implode( ",\n", $output );
share|improve this answer
add comment

Hope this helps,

$result = '';
foreach($main_array as $k=>$val)
{
   if($result!='')
      $result .= ',';

   $result .= "['".$val['id']."', '".$val['name']."']";
}

echo ($result);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.