0

I want to create an array from this string, stored in database:

$string = '"2148" => "50","2050" => "2","2403" => "1"';
$id_values = explode('=> "', $string);
foreach($id_values as $id => $value)
{
    $value_to_print .= '<img src="images/item_values/'.$id.'.gif"> - '.$value.'';
}

echo $value_to_print;

Manually defining the array works as expected:

$id_values = array("2148" => "50","2050" => "2","2403" => "1");
10
  • I've got this string that comes from a table in my database: Is the string in this format saved in your db?! Commented Apr 20, 2015 at 13:01
  • 2
    @Ghost That would have been my next comment after OP wrote: yes exactly.... – user3050478 3 mins ago You just have to up 2x * around the "why" :) Commented Apr 20, 2015 at 13:06
  • 1
    @Rizier123 so much for databases :-( thats why table columns are there for, should have used image_id or whatever name Commented Apr 20, 2015 at 13:11
  • 3
    @Ghost If I would have a country: abusing a database would be illegal! (OP: Please normalize your db!) Commented Apr 20, 2015 at 13:14
  • 1
    @FélixGagnon-Grenier > Indeed, and as I said I totally agree that besides helping him with the current question, it is wiser to also explain the best-practices, also to avoid further issues. Right now the issue might be solvable but if he continues like that he may indeed face some unsolvable issues, or big performance issues, and then be forced to rewrite a whole codebase. That is however very frustrating anyway :-) Commented Apr 20, 2015 at 13:36

7 Answers 7

5

It might be a better idea to save it in a better/more usable format, maybe using serialize:

The serialize function returns a string. You can then save that string in your database, at the same place you save your other string.

say this is your array:

$a = [2258=>"here",2259=>"then"];
$s = serialize($a);
// save the content of $s to your database

then, to get an array from the produced string:

// $s is the string from your database
$a = unserialize($s);
Sign up to request clarification or add additional context in comments.

2 Comments

where would tat array go in my database?
please understand that serialize() returns a simple string, the same format as your original string. just save it to your database the same way you did with the other one
2

$id isn't going to be the number from the original string - it will create a new one.

You could try this:

$string = '"2148" => "50","2050" => "2","2403" => "1"';
$id_values = array();
$bits = explode(",", $string);
foreach ($bits as $b) {
    $bobs = explode(" => ", $b);
    $id_values[$bobs[0]] = $bobs[1];
}
foreach($id_values as $id => $value){
    $value_to_print .= '<img src="images/item_values/'.$id.'.gif"> - '.$value.'';
}

That's untested but it should be fine.

In the future, use json_encode and json_decode to store and retrieve arrays.

Note: You probably want to get rid of the quotes too - just add

$b = str_replace('"', '', $b);

on the line before $bobs = explode(" => ", $b);

1 Comment

That worked for me, but I didn't understand the code tho... guess thats not ur fault
0

please try below code

$value_to_print = '';
$string = '"2148" => "50","2050" => "2","2403" => "1"';

$array = explode(',',$string);

foreach($array as $data){
       $indata = explode('=>',$data);           
       $value_to_print .= '<img src="images/item_values/'.trim($indata[0]).'.gif"> - '.trim($indata[1]).'';

}

Comments

0

I think the below code will help you to decode the given string array correctly. Here you need to explore first by ',' and then followed by '=>'

$string = '"2148" => "50","2050" => "2","2403" => "1"';

$value_to_print = "";

 $items = explode(",",$string);
foreach($items as $item)
{
  $pair = explode("=>",str_replace('"','',$item));
   $value_to_print .= '<img src="images/item_values/'.$pair[0].'.gif"> - '.$pair[1].'';
}

echo $value_to_print;

Here str_replace function can be used to remove the quotes

2 Comments

this is already in an answer from grim
yes. but it was not loading in ma system. just now loaded.
0
$string = '"2148" => "50","2050" => "2","2403" => "1"';   
$arr = array();

// split into key-val pairs
foreach(explode(',', $string) as $pair) {
    // we use a regular expression in case the input does not 
    // have spaces surrounding the "hash-rocket"
    // we also use str_replace to remove quotes
    $key_val = preg_split("/[\s*]=>[\s*]/", str_replace('"', "", $pair));
    // ensure pair is well formed
    if (count($key_val) === 2) {
        $arr[$key_val[0]] = $key_val[1];
    }
}

Output:

array(3) {
  [2148]=>
  string(2) "50"
  [2050]=>
  string(1) "2"
  [2403]=>
  string(1) "1"
}

1 Comment

I would do that if i had to work with data from a legacy database - otherwise I would use serialize as recommended by @félix-gagnon-grenier. However that would mean that you cannot query on this data and changing your DB structure might be a better alternative.
-1

I would just use eval instead. Basically make make it into a PHP expression and then use eval. Try this.

$string = '"2148" => "50","2050" => "2","2403" => "1"';
$string = 'return array(' . $string . ');';
$array = eval($string);

$value_to_print = '';

foreach($array as $id => $value){
    $value_to_print .= '<img src="images/item_values/'.$id.'.gif"> - '.$value.'';
}

echo $value_to_print;

1 Comment

What if the input contains user generated data? Oh sh*t.
-1

Please try the Below code Snipet It will work. enter image description here

<?php
    $string = '"2148" => "50","2050" => "2","2403" => "1"';
    $string = str_replace('"','',$string);

    $arrayList = explode(",",$string);
    $imageData = array();

    foreach($arrayList as $id=>$values){
        $arrayElemenets = explode(" => ",$values);
        $imageData[$arrayElemenets[0]] = $arrayElemenets[1];
    }

    $value_to_print = "";
    foreach($imageData as $id => $value){
        $value_to_print .= '<img src="images/item_values/'.$id.'.gif"> - '.$value.'';
    }

    echo $value_to_print;
?>

1 Comment

this is already in two other answers, from grim and Talifhani

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.