I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.
Related
Someone could be so nice to tell me how to do the following with 2 ore more arrays in PHP:
array 1 (a,b,c,d)
array 2 (1,2,3,4)
I would like to merge the two arrays in an unique array with the merged values:
Result: unique array (a-1,b-2,c-3,d-4).
Is there any function that does so? I could not find anything in the forum either on the web.
Thanks for all your answers but I guess that my arrays are a bit more structured because I need the final result for a dropdown field.
Now I have these 2 arrays:
$array1[] = array( 'text' => $hospital['value'], 'value' => $hospital['value'] );
$array2[] = array( 'text' => $company['value'], 'value' => $company['value'] );
I want to have a final array that contains: Hospital1 - Company1, Hospital2 - Company2, Hospital3 - Company3, etc..
Thanks
You can use array_map:
$result = array_map(function ($item1, $item2) {
return "$item1-$item2";
}, $array1, $array2);
Here is working demo.
You would have to create a loop to do this manually. it might look something like the following:
$a = array(a,b,c,d);
$b = array(1,2,3,4);
$c = array(); //result set
if(count($a) == count($b)){ // make sure they are the same length
for($i = 0; $i < count($a); $i++){
$c[] = $a[$i]."-".$b[$i];
}
}
print_r($c);
If i understand right, you can use array_combine where array 1 will be the key and array 2 the value.
Example usage:
$a = array(1,2,3,4);
$b = array(a,b,c,d);
$c = array_combine($a, $b);
var_dump($c);
If I had an array like this...
array('1','2','3','4','10')
... how could I remove elements before the element whose value I supply.
For example:
If I supplied 1 then array = (1,2,3,4,10)
If it were 2 then array = (2,3,4,10) //Remove the numbers before 2
If it were 3 then array = (3,4,10) //Remove the numbers before 3
If it were 4 then array = (4,10) //Remove the numbers before 4
If it were 10 then array = (10) //Remove all before the 10
I'm currently thinking of doing with using if else. But is there a way to do this using some kind of php array function itself.
Make use of array_search and array_slice
<?php
$arr=array_slice($arr, array_search('4',array('1','2','3','4','10')));
print_r($arr);
OUTPUT :
Array
(
[0] => 4
[1] => 10
)
Demo
Maybe this would help:
$myArray = array('1','2','3','4','10');
$x=3;
$myArray = array_splice($myArray, array_search($x, $myArray), count($myArray));
$myArray = array('1','2','3','4','10');
$value = 3;
$key = array_search($value, $myArray);
$myNewArray = array_splice($myArray, 0, $key);
$array = array_filter($array, function($item) use ($filterItem) {
return $item !== $filterItem;
});
Will filter out every item equal to $filterItem. array_filter on php.net
How can I delete duplicates in array?
For example if I had the following array:
$array = array('1','1','2','3');
I want it to become
$array = array('2','3');
so I want it to delete the whole value if two of it are found
Depending on PHP version, this should work in all versions of PHP >= 4.0.6 as it doesn't require anonymous functions that require PHP >= 5.3:
function moreThanOne($val) {
return $val < 2;
}
$a1 = array('1','1','2','3');
print_r(array_keys(array_filter(array_count_values($a1), 'moreThanOne')));
DEMO (Change the PHP version in the drop-down to select the version of PHP you are using)
This works because:
array_count_values will go through the array and create an index for each value and increment it each time it encounters it again.
array_filter will take the created array and pass it through the moreThanOne function defined earlier, if it returns false, the key/value pair will be removed.
array_keys will discard the value portion of the array creating an array with the values being the keys that were defined. This final step gives you a result that removes all values that existed more than once within the original array.
You can filter them out using array_count_values():
$array = array('1','1','2','3');
$res = array_keys(array_filter(array_count_values($array), function($freq) {
return $freq == 1;
}));
The function returns an array comprising the original values and their respective frequencies; you then pick only the single frequencies. The end result is obtained by retrieving the keys.
Demo
Try this code,
<?php
$array = array('1','1','2','3');
foreach($array as $data){
$key= array_keys($array,$data);
if(count($key)>1){
foreach($key as $key2 => $data2){
unset($array[$key2]);
}
}
}
$array=array_values($array);
print_r($array);
?>
Output
Array ( [0] => 2 [1] => 3 )
PHP offers so many array functions, you just have to combine them:
$arr = array_keys(array_filter(array_count_values($arr), function($val) {
return $val === 1;
}));
Reference: array_keys, array_filter, array_count_values
DEMO
Remove duplicate values from an array.
array_unique($array)
$array = array(4, "4", "3", 4, 3, "3");
$result = array_unique($array);
print_r($result);
/*
Array
(
[0] => 4
[2] => 3
)
*/
Is there a native function that works like combine_subarrays below?
$foo = array(
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
$n = 1; // desired element's position in each subarray
$bar = combine_subarrays($foo, $n);
// Result: $bar is array of all elements in 1st positions - [2,5,8]
Right now, I foreach through $foo and push the $nth element onto a new array that is then returned. If there's a native way to do it, it would be better.
A quick solution with global reference to $n would be:
$n = 1;
$bar = array_map(function($item) {
global $n;
return $item[$n];
},
$foo);
And the result is:
Array ( [0] => 2 [1] => 5 [2] => 8 )
There is no function that does exactly that but several ways to use the array functions instead of writing a loop. For example array_reduce*:
$bar = array_reduce($foo, function(&$result, $item) use ($n) {
$result[] = $item[$n]
});
**array_map is probably the better choice, it also preserves the original keys. See answer by #zeldi*
I have two preg_match() calls and i want to merge the arrays instead of replacing the first array. my code so far:
$arr = Array();
$string1 = "Article: graphics card";
$string2 = "Price: 300 Euro";
$regex1 = "/Article[\:] (?P<article>.*)/";
$regex2 = "/Price[\:] (?P<price>[0-9]+) Euro/";
preg_match($regex1, $string1, $arr);
//output here:
$arr['article'] = "graphics card"
$arr['price'] = null
preg_match($regex2, $string2, $arr);
//output here:
$arr['article'] = null
$arr['price'] = "300"
How may I match so my output will be:
$arr['article'] = "graphics card"
$arr['price'] = "300"
?
You could use preg_replace_callback and handle the merging inside the callback function.
If it were me this is how I would do it, this would allow for easier extension at a later date, and would avoid using a callback function. It could also support searching one string easily by replacing $strs[$key] and the $strs array with a singular string var. It doesn't remove the numerical keys, but if you are only ever to go on accessing the associative keys from the array this will never cause a problem.
$strs = array();
$strs[] = "Article: graphics card";
$strs[] = "Price: 300 Euro";
$regs = array();
$regs[] = "/Article[\:] (?P<article>.*)/";
$regs[] = "/Price[\:] (?P<price>[0-9]+) Euro/";
$a = array();
foreach( $regs as $key => $reg ){
if ( preg_match($reg, $strs[$key], $b) ) {
$a += $b;
}
}
print_r($a);
/*
Array
(
[0] => Article: graphics card
[article] => graphics card
[1] => graphics card
[price] => 300
)
*/
You can use array_merge for this if you store your results in two different arrays.
But your output depicted above is not correct. You do not have $arr['price'] if you search with regex1 in your string but only $arr['article']. Same applies for the second preg_match.
That means if you store one result in $arr and one in $arr2 you can merge them into one array.
preg_match does not offer the functionality itself.
Use different array for second preg_match ,say $arr2
Traverse $arr2 as $key => $value .
Choose non null value out of $arr[$key] and $arr2[$key], and write that value to $arr[$key].
$arr will have required merged array.
This should work for your example:
array_merge( // selfexplanatory
array_filter( preg_match($regex1, $string1, $arr)?$arr:array() ), //removes null values
array_filter( preg_match($regex2, $string2, $arr)?$arr:array() )
);