PHP Comma Delimiter or Explode for Foreach Loop [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 7 months ago.
I have a drag and drop JS plugin that saves strings as the following:
["кровать","бегемот","корм","валик","железосталь"]
I have found that I can use str_replace in an array to remove both brackets and " char. The issue that I now have is that I have a invalid argument for passing through the foreach loop as it cannot distinguish each individual word.
$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str = str_replace(str_split('[]"'), '', $bar);
foreach($new_str as $arr){
echo $arr;
}
So the data now outputted looks as follows (if I were to echo before the foreach loop):
кровать,бегемот,корм,валик,железосталь
Is there anyway in which I can use a comma as a delimeter to then pass this through the foreach, each word being it's own variable?
Is there an easier way to do this? Any guidance greatly appreciated!

Technically, you can use explode, but you should recognize that you're getting JSON, so you can simply do this:
$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str = json_decode($bar);
foreach($new_str as $arr){
echo $arr;
}
With no weird parsing of brackets, commas or anything else.

The function you need is explode(). Take a look here:
http://www.w3schools.com/php/func_string_explode.asp
Look at the following code:
$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str = str_replace(str_split('[]"'), '', $bar);
$exploding = explode(",", $new_str);
foreach($exploding as $token){
echo $token;
}

It looks like you've got a JSON string and want to convert it to an array. There are a few ways to do this. You could use explode
like this:
$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str = str_replace(str_split('[]"'), '', $bar);
$new_str_array = explode($new_str);
foreach($new_str_array as $arr){
echo $arr;
}
or you could use json_decode
like this:
$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str_array = json_decode($bar);
foreach($new_str_array as $arr){
echo $arr;
}

<?php
$aa = '["кровать","бегемот","корм","валик","железосталь"]';
$bb = json_decode($aa);
foreach($bb as $b)
echo $b."\n";
?>
and the results is,
кровать
бегемот
корм
валик
железосталь

Related

How right print result search preg_replace inside fetch_assoc() result mysql?

$i = $result->fetch_assoc();
preg_replace("/\{(.*?)\}/", $i["$1"], $content);
Error - Undefined variable: $1
// $1 - 'string'; // result search preg_replace()
// $i['string'] = 'hello';
How right syntax will be for print 'hello'?
ok next time please spend a little more time on asking the question:
<?php
$i['string'] = 'zzzzzzzzzzzzzzzzzzzzzz';
$content = "test test test {string} testtesttesttesttest";
$x=preg_replace_callback("/\{(.*?)\}/", function($m) use($i){
return $i[$m[1]];
}, $content);
echo $x;
demo: http://codepad.viper-7.com/u29uKh
for this particular approach you need to use preg_replace_callback() requires PHP 5.3+
You can make your replacements faster using strtr. To do that, you only need an associative array, but this time, all keys must be enclosed between curly brackets.
$i = $result->fetch_assoc();
$keys = array_map(function($k) { return '{' . $k . '}'; }, array_keys($i));
$trans = array_combine($keys, $i);
$content = strtr($content, $trans);
A variable name can't start with a number in PHP. It must start with an underscore or letter.

In comma delimited string is it possible to say "exists" in php

In a comma delimited string, in php, as such: "1,2,3,4,4,4,5" is it possible to say:
if(!/*4 is in string bla*/){
// add it via the .=
}else{
// do something
}
In arrays you can do in_array(); but this isn't a set of arrays and I don't want to have to convert it to an array ....
Try exploding it into an array before searching:
$str = "1,2,3,4,4,4,5";
$exploded = explode(",", $str);
if(in_array($number, $exploded)){
echo 'In array!';
}
You can also replace numbers and modify the array before "sticking it back together" with implode:
$strAgain = implode(",", $exploded);
You could do this with regex:
$re = '/(^|,)' + preg_quote($your_number) + '(,|$)/';
if(preg_match($re, $your_string)) {
// ...
}
But that's not exactly the clearest of code; someone else (or even yourself, months later) who had to maintain the code would probably not appreciate having something that's hard to follow. Having it actually be an array would be clearer and more maintainable:
$values = explode(',', $your_string);
if(in_array((str)$number, $values)) {
// ...
}
If you need to turn the array into a string again, you can always use implode():
$new_string = implode(',', $values);

separate with commas

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

How do I place a comma between each character in a string with PHP? [duplicate]

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

How can I use a string to get a value from a multi dimensional array?

Say this is my string
$string = 'product[0][1][0]';
How could I use that string alone to actually get the value from an array as if I had used this:
echo $array['product'][0][1][0]
I've messed around with preg_match_all with this regex (/\[([0-9]+)\]/), but I am unable to come up with something satisfactory.
Any ideas? Thanks in advance.
You could use preg_split to get the individual array indices, then a loop to apply those indices one by one. Here's an example using a crude /[][]+/ regex to split the string up wherever it finds one or more square brackets.
(Read the [][] construct as [\]\[], i.e. a character class that matches right or left square brackets. The backslashes are optional.)
function getvalue($array, $string)
{
$indices = preg_split('/[][]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
foreach ($indices as $index)
$array = $array[$index];
return $array;
}
This is prettttty hacky, but this will work. Don't know how much your array structure is going to change, either, this won't work if you get too dynamic.
$array = array();
$array['product'][0][1][0] = "lol";
$string = 'product[0][1][0]';
$firstBrace = strpos( $string, "[" );
$arrayExp = substr($string, $firstBrace );
$key = substr( $string, 0, $firstBrace );
echo $arrayExp, "<br>";
echo $key, "<br>";
$exec = "\$val = \$array['".$key."']".$arrayExp.";";
eval($exec);
echo $val;
What about using eval()?
<?php
$product[0][1][0] = "test";
eval ("\$string = \$product[0][1][0];");
echo $string . "\n";
die();
?>

Categories