Solved

data conversion, array to json perhaps

Posted on 2013-12-18
13
208 Views
Last Modified: 2014-01-10
I have an array like this:

["Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7"]

and I need to convert it into this:

[{
        id: "1",
        label: "Tag 1"
    }, {
        id: "2",
        label: "Tag 2"
    }, {
        id: "3",
        label: "Tag 3"
    }, {
        id: "4",
        label: "Tag 4"
    }, {
        id: "5",
        label: "Tag 5"
    }, {
        id: "6",
        label: "Tag 6"
    }, {
        id: "7",
        label: "Tag 7"
    }]


Seems easy enough but I am having trouble figuring it out.
0
Comment
Question by:rjohnsonjr
  • 4
  • 3
  • 2
  • +2
13 Comments
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 39727809
Use this:

$arrSrc = array("Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7");
$arrDst = array();
for ($i = 0; $i < count($arrSrc); $i++) {
    $arrDst[] = array("id " . $i + 1, "label: " . $arrSrc[$i]);
}
echo "<pre>";
var_dump($arrDst);

Open in new window

0
 
LVL 6

Author Comment

by:rjohnsonjr
ID: 39727829
I need it to output on the page like I have it displayed.

I am passing back to a javascript call and doing an eval()
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39727840
In JSON, line spacing does not matter outside of the tags.  http://json.org/

This appears to generate the correct JSON string.
http://www.laprbass.com/RAY_temp_rjohnsonjr.php

<?php // RAY_temp_rjohnsonjr.php
error_reporting(E_ALL);
echo '<pre>';


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28321692.html


// TEST DATA FROM THE POST AT EE
$str = <<<EOD
["Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7"]
EOD;

// MAKE AN ARRAY
$arr = json_decode($str);

// CREATE THE OUTPUT ARRAY OF OBJECTS
$out = array();

// ITERATE OVER THE ARRAY OF TAGS
foreach ($arr as $tag)
{
    // THE TAG NUMBER WILL BE USED TO CREATE THE 'id' VALUE
    $xyz = explode(' ', $tag);

    // ONE OBJECT FOR EACH TAG
    $std = new stdClass;
    $std->id = $xyz[1];
    $std->label = $tag;

    // STORE THE OBJECT IN THE ARRAY OF OBJECTS
    $out[] = $std;
}

// CREATE THE JSON STRING
$new = json_encode($out);
echo $new;

Open in new window

Best regards, ~Ray
0
 
LVL 10

Accepted Solution

by:
acbxyz earned 500 total points
ID: 39727841
If you only want to display the result var_dump is good, to work with the result it should not be used.
There is a function to convert a php array to a json string: http://www.php.net/manual/en/function.json-encode.php

To get the desired output you first have to convert your array to an associated one.
$input = array("Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7");
$temp = array();
foreach ($input as $id => $label) {
    $temp[] = array('id' => $id, 'label' => $label);
}
echo str_replace(",", ",\n", json_encode($temp));

Open in new window

You can replace the foreach with array_map() if you prefer.

Edit: the str_replace at the last echo is just for nice output of debugging. For JS it doesn't matter.
0
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 39727848
I apologize for misunderstanding: the following code convert the array into a string.

$arrSrc = array("Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7");
$str = '[';
for ($i = 0; $i < count($arrSrc); $i++) {
    $str .= "{id " . $i + 1, "label: " . $arrSrc[$i])},;
}
$str = substr($str, 0, (strlen($str)-1));
$str .= "]";
echo "<pre>";
echo $str;

Open in new window

0
 
LVL 10

Expert Comment

by:acbxyz
ID: 39728117
With this little change, it does:
-    $temp[] = array('id' => $id, 'label' => $label);
+    $temp[] = array('id' => ($id + 1), 'label' => $label);

Open in new window

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39728156
@abcxyz: Yes, that is one of the problems of a "soft" problem definition.  Did the author really mean that the "id" property should match the number in the "label" property? Or did thie author mean that the "id" property should be numbered from 1, without regard to the number in the "label" property?  Or is this irrelevant and the "id" is a complete red herring?  There is no way to know since the author asked for one thing, then accepted something that did not match the request!  That's why I reopened it, so we can get clarification.  I'm sure the author can revisit the question. ~Ray
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 39728213
From reading the question verbatim it can not be done. The author wants to produce a valid output but the keys in his desired result are not quoted so it will never convert to or from a json string - just can't work.

If the author clarifies the question and be more specific I am sure they will get their answer.
0
 
LVL 6

Author Comment

by:rjohnsonjr
ID: 39728266
The answer did match my request obviously that is why I accepted it as the answer.  I copied and pasted the code and it worked perfectly.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39728308
0
 
LVL 6

Author Comment

by:rjohnsonjr
ID: 39728323
Ray,

Without sounding rude, how about you as the expert tell me why your solution is better than @abcxyz's solution?

Here is how I made my decision.  I clicked the email that came in with his answer first.  I saw it was 3 lines of code long.   I tried it.  It worked exactly as needed.  I then scrolled up and saw your solution.  I did not see a reason to switch out already working code.  His code was shorter and more concise.  Yes you were more thorough with your code commenting.

Unless you have some solid evidence that your solution is a better fitI am inclined to give @abcxyz the points because his solution was the most concise and works like a charm.

Thank You.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39730879
@rjohnsonjr, I don't really care which answer you accept.  The answer I posted gave the result you asked for and it was posted before the answer you accepted.  The answer you accepted did not give the answer you asked for.  The central issue is described in the post here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28321692.html#a39728156

If you do not care about the relationship of the "id" and the number in the "Tag XX" data field, then naturally you would not establish a relationship by making the numbers correlate!  Indexes in PHP are naturally started from zero, and the correct output, if you do not care, might be like this:
[{
        id: "0",
        label: "Tag 1"
    }, {
        id: "1",
        label: "Tag 2" ... etc... 

Open in new window

But since you posted a request for different output in the original question, I created a response based on the understanding that you wanted the output you asked for!

For better or worse, computer programming is an activity that requires precision and meticulous attention to detail.  If someone asks for "one" and the response is "zero" that seems to misunderstand the request.

Please do whatever you think is right for your own needs and the good of the community that might one day read your question and the accepted answer.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now