Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap array into custom string based on the array

Tags:

arrays

string

php

So I have a list that looks like the following:

 $mylist = array('100003028593816', '1784394111', '100008137385157', '100000462582000','100001633550680', '100000757743079');

(This list can vary based on different inputs, etc. This is just an example)

I want to create a STRING from that array that looks like the following.

$string = '{"100003028593816":1,"1784394111":1,"100008137385157":1,"100000462582000":1,"100001633550680":1,"100000757743079":1}'

(NOTE: See how they are the same values as above, they're just wrapped up differently. That's how they need to be posted. So I pretty much want to take the values from the array and wrap them as {"value1":1,"value2":1} etc.

In python I used

 mystring= '{' + ','.join(map(lambda x: '"' + x + '":1', mylist)) + '}'

Which did the trick. I'm just not sure what the proficent way to do it in PHP is.

like image 455
user1687621 Avatar asked Dec 05 '25 03:12

user1687621


1 Answers

Just use array_fill_keys, and encode the array with json_encode:

echo json_encode(array_fill_keys($mylist, 1));

Output:

{"100003028593816":1,"1784394111":1,"100008137385157":1,"100000462582000":1,"100001633550680":1,"100000757743079":1}
like image 114
Federkun Avatar answered Dec 07 '25 20:12

Federkun