Question

I have this php associative array.

array(
                'Location_1' => 'Link_1',
                'Location_2' => 'Link_2'
    )

I would like to convert it into a json output using json_encode() that looks like this;

[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]

How can this be done? The challenging part to me seems like how to add the Location_name and Link_name in front. Thank you very much.

Was it helpful?

Solution

<?php
// original array
$a = array(
   'Location_1' => 'Link_1',
   'Location_2' => 'Link_2'
);
// transform
$b = array();
foreach($a as $key=>$value) {
    $b[] = array('Location_name'=>$key, 'Link_name'=>$value);
}

// output
echo json_encode($b);

?>

Result:

[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]

OTHER TIPS

You Can use StdClass anonymous Objects.

<?php


$newArray = array();

$array = array(
  'Location_1' => 'Link_1',
  'Location_2' => 'Link_2'
);



foreach ($array as $key => $value) {

  $object     = new StdClass();
  $object->Location_name = $key;
  $object->Link_name = $value;
  $newArray[] = $object;
}


var_dump(json_encode($newArray));   

So first things first:

convert it into a json output using json_encode() that looks like this

This is not possible. json_encode just encodes arrays to JSON, you need to do the formatting work yourself.

And on that note

array_map should do the trick.

Try this:

$arr = array(
    'Location_1' => 'Link_1',
    'Location_2' => 'Link_2'
);

$output = array_map( 
    function( $key, $val ){
        return array(
            "Location_name" => $key,
            "Link_name" => $val
        );
    }, array_keys( $arr ), $arr );

echo json_encode( $output );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top