How to make an array of this string? - php

I have a string like this:
$str = '"list":["test 1","test 2"]';
How to make an array:
$arr['list'] = array('test 1','test 2');
?

Make it a valid JSON string and use json_decode function like this:
$str = '"list":["test 1","test 2"]';
$arr = json_decode('{' . $str . '}', true);
print_r($arr);
OUTPUT:
Array
(
[list] => Array
(
[0] => test 1
[1] => test 2
)
)

Related

PHP String(which contain array of object) to Array conversion

Suppose I have a string (which contain array of objects):
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
My goals is to get the output to look like this when I print_r:
Array
(
[0] => Array
(
[test] => 1
[anothertest] => 2
)
[1] => Array
(
[test] => 3
[anothertest] => 4
)
)
I tried to json_decode($string) but it returned NULL
Also tried my own workaround which is kinda solved the problem,
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = substr($string, 1, -1);
$string = str_replace("'","\"", $string);
$string = str_replace("},","}VerySpecialSeparator", $string);
$arrayOfString = explode("VerySpecialSeparator",$string);
$results = [];
foreach($arrayOfString as $string) {
$results[] = json_decode($string, true);
}
echo "<pre>";
print_r($results);
die;
But is there any other ways to solve this?
As per your given data, if quotes will be corrected, then you will get your desired output, so get it done like below:
<?php
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = str_replace("'",'"', $string);
print_r(json_decode($string,true));
https://3v4l.org/PDI7O

Compare a string and a php array and only show the matches

I have a string that looks like this:
"illustration,drawing,printing"
I have an array that looks like this:
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
How can I compare the two and only display the terms that exist in both the string and array?
So in the above example, I would want to output something that looks like this:
SKILLS: illustration, drawing
Thank you!
use explode(), array_intersect() and implode()
<?php
$string = "illustration,drawing,printing";
$array = Array (
0 => 'illustration',
1 => 'drawing',
2 => 'painting',
3 => 'ceramics'
);
$stringArray = explode(',',$string);
$common = array_intersect($stringArray,$array);
echo "Skills :".implode(',',$common);
https://3v4l.org/StqYN
You can do something like this:
Function:
function functionName($string, $array){
$skills = '';
// Create a temp array from your string breaking appart from the commas
$temparr = explode(",", $string);
// Iterate through each of the words now
foreach($temparr as $str){
// Check to see if our current string is in the array provided
if(in_array($str, $array)){
// If it is, then add it to the string "skills"
$skills .= "${str}, ";
}
}
// Cut the last space and comma off the end of the str.
$skills = substr($skills, 0, strlen($skills) - 2);
// Return our results
return 'SKILLS: '.$skills;
}
Usage:
$string = "illustration,drawing,printing";
$array = Array (
0 => "illustration",
1 => "drawing",
2 => "painting",
3 => "ceramics"
);
// Just input our string and the array we want to search through
echo(functionName($string, $array));
Live Demos:
https://ideone.com/qyqgzo
http://sandbox.onlinephpfunctions.com/code/65dc988370ad8ce61ab5ccbc232af4bcf8bd3d42
You could replace the comma , and join the string words on OR | and grep for them. This will match the word anywhere in each array element:
$result = preg_grep("/".str_replace(",", "|", $string)."/", $array);
If you want exact matches only then: "/^(".str_replace(",", "|", $string).")$/"
Firstly convert that string into array.
use array_intersect();
$str = "illustration,drawing,printing";
$ar1 = explode(",",$str);
print_r ($ar1);
$ar2 = Array ("illustration","drawing","painting","ceramics");
echo "<br>";
print_r ($ar2);
$result = array_intersect($ar1, $ar2);
echo "Skills :".implode(',',$result);
OUTPUT:
Array (
[0] => illustration
[1] => drawing
[2] => printing
)
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
SKILLS: illustration, drawing

Create a multicolumn array in PHP from string

I want to create a multicolumn array from a string where the spearator for the first level array is ";" and for the second level array is ","
This string is given:
$string = ("de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3")
This is the structure of the array that i want as result:
Array
(
array([de] => text1, text2, text3),
array([en] => text1, text2, text3),
array([pl] => text1, text2, text3),
)
The solution using array_map, substr, strpos and explode functions:
$string = ("de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3");
$items = array_map(function($v){
$sep_pos = strpos($v, ","); // position of key/values separator
return [substr($v, 0, $sep_pos) => substr($v, $sep_pos + 1)];
}, explode(";", $string));
print_r($items);
The output:
Array
(
[0] => Array
(
[de] => text1,text2,text3
)
[1] => Array
(
[en] => text1,text2,text3
)
[2] => Array
(
[pl] => text1,text2,text3
)
)
You can use array_map and pass array by using explode, and inside callback you can explode again with , and store it in a variable.
there after you can grab the value using array_shift, which needed to be used as a key, and return a new array.
$string = "de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3";
$result = array_map(function($value) {
$temp = explode(',', $value);
return [array_shift($temp) => implode(',', $temp)];
}, explode(';', $string));
print_r($result);
Example: https://eval.in/581893
Try:
$string = "de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3";
$mainArr = explode(";",$string);
$finalArr = array();
foreach($mainArr as $arr) {
$tempArr = explode(",",$arr);
reset($tempArr);
$mainK = $tempArr[0];
unset($tempArr[key($tempArr)]);
$finalArr[][$mainK] = implode(",", $tempArr);
}
print '<pre>';print_r($finalArr);print '</pre>';
Output:
Array
(
[0] => Array
(
[de] => text1,text2,text3
)
[1] => Array
(
[en] => text1,text2,text3
)
[2] => Array
(
[pl] => text1,text2,text3
)
)
Try This Code
$string = "de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3";
$array1 = explode(';', $string);
foreach($array1 as $value){
$temp=explode(',', $value);
$key=$temp[0];
unset($temp[0]);
$new_array[][$key]=$temp;
}

Turn string into array

This should be a simple task, but I guess my head is a bit overheated currently.
How do I correctly turn a GET string with the value "status[30]" into an array, like:
array ( status => 30 );
I could use something like this:
$arr = array ( 'status' => str_replace( array( 'status[', ']' ), null, $_GET['status'] ) );
but there has to be a better way.
$arr = [];
$getValue = "status[30]";
if (preg_match('#(\w+)\[(\w+)\]#', $getValue, $matches))
$arr[$matches[1]] = $matches[2];
print_r($arr);
Output:
Array
(
[status] => 30
)

Merge a string in an array

I have this array:
$fields = $_GET['r'];
Which has some ids, for example:
Array (
[0] => 3134
[1] => 3135 )
and then I have this string in $tematiche:
3113,3120
How can I marge this string in the first array? Also, how can I remove the equals id (if any)?
Try,
$fields = array_unique(array_merge($fields,explode(",",$tematiche)));
echo "<pre>";
print_r($fields);
Try this :
$fields = $_GET['r'];
$string = '3113,3120';
$array = explode(",",$string);
$res_array = array_unique(array_merge($fields,$array));
echo "<pre>";
print_r($res_array);
Output :
Array (
[0] => 3134
[1] => 3135
[2] => 3113
[3] => 3120
)
A combination of explode(), array_merge() and array_unique() would be suitable.
// Make $tematiche into an array
$tematiche_array = explode(',', $tematiche);
// Merge the two arrays
$merged_array = array_merge($fields, $tematiche_array);
// Remove all duplicate values in the array
$unique_array = array_unique($merged_array);
Please try like this. This should work for you.
$a = explode(',', '3113,3120');
print_r(array_merge($fields,$a));

Categories