0

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.

3
  • try getting our PHP model in line with your JSON Model, and you'll get the rest for free. Note that the JSON you're showing is an array of hashes (associative arrays) but in PHP you aren't capturing this difference. Commented Mar 19, 2014 at 3:36
  • Do you mean the php associative array is inefficient for my kind of JSON output? Sorry, I am not familiar with php. Commented Mar 19, 2014 at 3:39
  • NO, I'm just saying that you need to reformat your data so it's in the same format as the JSON. Commented Mar 19, 2014 at 3:48

3 Answers 3

6
<?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"}]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.