Search code examples
phparraysjsonencode

Reindex and json encode associative rows of a 2d array


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 below?

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

Solution

  • 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 );