split a comma separated string in a pair of 2 using php - php

I have a string having 128 values in the form of :
1,4,5,6,0,0,1,0,0,5,6,...1,2,3.
I want to pair in the form of :
(1,4),(5,6),(7,8)
so that I can make a for loop for 64 data using PHP.

You can accomplish this in these steps:
Use explode() to turn the string into an array of numbers
Use array_chunk() to form groups of two
Use array_map() to turn each group into a string with brackets
Use join() to glue everything back together.
You can use this delicious one-liner, because everyone loves those:
echo join(',', array_map(function($chunk) {
return sprintf('(%d,%d)', $chunk[0], isset($chunk[1]) ? $chunk[1] : '0');
}, array_chunk(explode(',', $array), 2)));
Demo
If the last chunk is smaller than two items, it will use '0' as the second value.

<?php
$a = 'val1,val2,val3,val4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = array(array_shift($buffer), array_shift($buffer)); }
return $result;
}
$result = x($a);
var_dump($result);
?>
Shows:
array(2) { [0]=> array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" } [1]=> array(2) { [0]=> string(4) "val3" [1]=> string(4) "val4" } }
If modify it, then it might help you this way:
<?php
$a = '1,2,3,4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = sprintf('(%d,%d)', array_shift($buffer), array_shift($buffer)); }
return implode(',', $result);
}
$result = x($a);
var_dump($result);
?>
Which shows:
string(11) "(1,2),(3,4)"

Related

php function for rading out values from string

i want to make a php loop that puts the values from a string in 2 different variables.
I am a beginner. the numbers are always the same like "3":"6" but the length and the amount of numbers (always even). it can also be "23":"673",4:6.
You can strip characters other than numbers and delimiters, and then do explode to get an array of values.
$string = '"23":"673",4:6';
$string = preg_replace('/[^\d\:\,]/', '', $string);
$pairs = explode(',', $string);
$pairs_array = [];
foreach ($pairs as $pair) {
$pairs_array[] = explode(':', $pair);
}
var_dump($pairs_array);
This gives you:
array(2) {
[0]=>
array(2) {
[0]=>
string(2) "23"
[1]=>
string(3) "673"
}
[1]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "6"
}
}
<?php
$string = '"23":"673",4:6';
//Remove quotes from string
$string = str_replace('"','',$string);
//Split sring via comma (,)
$splited_number_list = explode(',',$string);
//Loop first list
foreach($splited_number_list as $numbers){
//Split numbers via colon
$splited_numbers = explode(':',$numbers);
//Numbers in to variable
$number1 = $splited_numbers[0];
$number2 = $splited_numbers[1];
echo $number1." - ".$number2 . "<br>";
}
?>

PHP extract number only from result explode

I have explode here is the result of var_dump:
and I want get the result from explode:
7 [remove other string]
0 [if contain "-"]
0 [if contain "-"]
0 [if contain "-"]
Here, I just used comma as delimiter:
var_dump (explode(",", $rowData[0][13]));
die();
Does anyone have the solution to solved this?
Thank You.
Use array_map() function and in it use filter_var() to sanitize number value.
Try
$rowData = ['JJ7', 'B-', 'S-', 'M-'];
$result = array_map(function($v) {
return abs((int) filter_var($v, FILTER_SANITIZE_NUMBER_INT));
}, $rowData );
var_dump( $result );
//output
// array(4) { [0]=> int(7) [1]=> int(0) [2]=> int(0) [3]=> int(0) }
<?php
$data_result = explode(",", $rowData[0][13])
for($data_count=0;$data_count<count($data_result);$data_count++)
{
if(substr($data_result[$data_count], -1) == '-')
{
echo $data_result[$data_count]
}
}
?>

PHP Change multidimensional array structure

Hello I've multidimensional array that looks like that:
array(13890) {
[0]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(111)
["nazwa"]=>
string(6) "DŻUMA"
}
["ProjectIcd"]=>
array(0) {
}
}
[1]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(566)
["nazwa"]=>
string(7) "ŚWINKA"
}
["ProjectIcd"]=>
array(0) {
}
}
An so on.
I want to change it so it looks something like that:
array(13890) {
[0]=> array(2) {
["id"]=>
int(111)
["text"]=>
string(6) "DŻUMA"
}
How is this possible to do?
I want to add, I want to convert the array to json and feed it to select2 js in ajax.
Will that be a problem or not?
Short solution using array_map function:
// $arr is your initial array
$new_arr = array_map(function($a){
return ['id' => $a['Icd']['id'], 'text' => $a['Icd']['nazwa']];
}, $arr);
So you can simple create a new array and add there the values, which you want based on the old array. Then you convert the array to a json string with the php function json_encode():
$array = array("text"=>$old_array[0]["Icd"]["nazwa"]);
echo json_encode($array);
I hope this is something that you want.
$res = [];
$i = 0;
foreach($array as $arr) {
//get keys
if (count($arr) > 0) {
$keys = array_keys($arr);
// loop through the keys and fetch data of those keys
// put in array
foreach($keys as $key) {
if ($arr[$key]) {
$res[$i]['id'] = $arr[$key]['id'];
$res[$i]['text'] = $arr[$key]['nazwa'];
}
$i++;
}
}
}
print_r($res);
// To change array to json
echo json_encode($res);

How to create an array using array_fill function in PHP?

I want to create an array like below
array(2) {
[0]=>
array(2) {
[0]=>
int(1)
[1]=>
int(0)
}
[1]=>
array(2) {
[0]=>
int(2)
[1]=>
int(0)
}
}
Here first element of the inner array will be incremental and second element will always be 0. The outer array length should be 30. I spent a lot of of time on it but couldn't solve it by my one.
Can any one of you help me ?
Thanks
You could do it using array_map() and range():
$o = array_map(function($a) { return array($a, 0); }, range(1, 30));
Demo
The array_fill() function creates an array where all elements are identical. You're asking for an array where the elements aren't all identical, so it's not something you can create simply by using array_fill()....
$array = array_fill(0, 2, array_fill(0, 2, 0));
array_walk($array, function(&$value, $key) { $value[0] = $key+1; });
Maybe you want something like this?
<?php
function initArray() {
$array = array();
for ($i = 1; $i <= 30; $i++) {
$array[] = array($i, 0);
}
return $array;
}
// now call the initArray() function somewhere you need it
$myFancyArray = initArray();
?>

Create string to put in an IN statement from an array of arrays

I have an array of arrays that look like this:
array(40) {
[0]=>
array(2) {
["id"]=>
string(2) "ta"
["size"]=>
int(2)
[1]=>
array(2) {
["id"]=>
string(2) "tq"
["size"]=>
int(4)
....
I want to be able to get all the sizes in a way that I can do a query like this:
IN (2,4)
so... For each array, get the size key: IN (size,size,size...)
Thanks!
You could do something like this:-
$sizes = implode(',', array_map(function($v) { return $v['size']; }, $array));
Then just pass $sizes to your IN query
edit
In response to your comment below, you can use array_unique to remove duplicate sizes, eg:
$sizes = implode(',', array_unique(array_map(function($v) { return $v['size']; }, $array)));
Here you go:
$a = array("id"=>"ta","size"=>2);
$b = array("id"=>"tq","size"=>4);
$c = array($a,$b);
$in = array();
foreach ($c as $key=>$value) {
if(array_key_exists("size", $value)){
$in[] = $value["size"];
}
}
echo implode(",", $in);
$sizes = array();
foreach($array as $value) {
$sizes[] = $value['size'];
}
$query = implode(',', $sizes);
query ..." IN ($query) "..

Categories