how to explode the index of an array in PHP? - php

I have an array like
Array
(
[select_value_2_1] => 7
)
I want to explode index into Array ([0]=select_value, [1]=2, [2]=1)

Use array_keys to get your keys:
http://php.net/manual/en/function.array-keys.php
Or use a foreach loop:
foreach($elements as $key => $value){
print_r (explode("_", $key));
}

You can't just use explode() because it will also separate select from value. You could alter your output so that instead you have array keys like selectValue_2_1.
Then you can do what you want:
$items = array('selectValue_2_1' => 1);
foreach ($items as $key => $value) {
$parts = explode('_', $key);
}
That will yield, for example:
array('selectValue', '2', '1');
You can use array_keys() to extract the keys from an array.

Or if you want to split the keys as in your example, use a more complex function:
foreach ($array as $key=>$value) {
$key_parts = preg_split('/_(?=\d)/', $key);
}

If you always have the exact pattern, you could use a regular expression to extract the values:
foreach ($array as $key=>$value) {
if(preg_match('/(select_value)_(\d+)_(\d+)/', $key, $result)) {
array_shift($result); // remove full match
}
}
The performance of this may suck because you have a regular expression and an array operation.

<?php
$arr=array("select_value_2_1" => 7);
$keys= array_keys($arr);
$key=$keys[0];
$new_arr=explode("_",$key);
print_r($new_arr);
?>

Related

Merge array with common value

I have two arrays namely arr and arr2.
var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}];
var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}];
Is it possible to get array below shown from above two arrays?
result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}];
If i use array_merge then i get answer as
result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}];
You must decode JSON to arrays, manually merge them and again encode it to JSON :)
<?php
$arr = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$arr2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);
$result = [];
foreach ($arr as &$item) {
if (empty($arr2))
break;
foreach ($arr2 as $key => $item2) {
if ($item['month'] === $item2['month']) {
$item = array_merge($item, $item2);
unset($arr2[$key]);
continue;
}
}
}
if (!empty($arr2))
$arr = array_merge($arr, $arr2);
echo json_encode($arr);
The first function that comes to mind is array_merge_recursive(), but even if you assign temporary associative keys to the subarrays, you end up with multiple January values in a new deep subarray.
But do not despair, there is another recursive function that can do this job. array_replace_recursive() will successfully merge these multidimensional arrays so long as temporary associative keys are assigned first.
Here is a one-liner that doesn't use foreach() loops or if statements:
Code: (Demo)
$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true);
$arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true);
echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month'))));
Output:
[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]
The breakdown:
echo json_encode( // convert back to json
array_values( // remove the temp keys (reindex)
array_replace_recursive( // effectively merge/replace elements associatively
array_column($arr,NULL,'month'), // use month as temp keys for each subarray
array_column($arr2,NULL,'month') // use month as temp keys for each subarray
)
)
);
You should write your own function to do that
$res = [];
foreach ($arr as $item) {
$res[$item['month']] = $item;
}
foreach ($arr2 as $item) {
$res[$item['month']] = isset($res[$item['month']]) ? array_merge($res[$item['month']], $item) : $item;
}
var_dump($res);

How to extract all 2nd level values (leaf nodes) from a 2-dimensional array and join with commas?

How can I get the list of values from my array:
[data] => Array
(
[5] => Array
(
[0] => 19
[1] => 18
[2] => 20
)
[6] => Array
(
[0] => 28
)
)
Expected output result string will be: 19,18,20,28
Thanks!
With one line, no loop.
echo implode(',', call_user_func_array('array_merge', $data));
Try it here.
Use following php code:
$temp = array();
foreach($data as $k=>$v){
if(is_array($v)){
foreach($v as $key=>$value){
$temp[] = $value;
}
}
}
echo implode(',',$temp);
Use following code.
$string = '';
foreach($yourarray as $k){
foreach($k as $l){
$string. = $l.",";
}
}
Just loop over sub arrays. Store values to $result array and then implode with ,
$result = array();
foreach ($data as $subArray) {
foreach ($subArray as $value) {
$result[] = $value;
}
}
echo implode(',', $result);
$data = array(5 => array(19,18,20), 6 => array(28));
foreach ($data as $array) {
foreach ($array as $array1) {
echo $array1.'<br>';
}
}
Try this one. It will help you
Since all of the data that you wish to target are "leaf nodes", array_walk_recursive() is a handy function to call.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
array_walk_recursive($data,function($v){static $first; echo $first.$v; $first=',';});
Output:
19,18,20,28
This method uses a static declaration to avoid the implode call and just iterates the call of echo with preceding commas after the first iteration. (no temporary array generated)
I haven't really taken the time to consider any fringe cases, but this is an unorthodox method that will directly provide the desired output string without loops or even generating a new, temporary array. It's a tidy little one-liner with a bit of regex magic. (Regex Demo) It effectively removes all square & curly brackets and double-quoted keys with trailing colons.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
echo preg_replace('/[{}[\]]+|"\d+":/','',json_encode($data));
Output:
19,18,20,28
To be clear/honest, this is a bit of hacky solution, but I think it is good for SO researchers to see that there are often multiple ways to achieve any given outcome.
try with this..
foreach($data as $dataArr){
foreach ($subArray as $value) {
$res[] = $value;
}
}
echo implode(',', $res);
Just use nested foreach Statements
$values = array();
foreach($dataArray as $key => $subDataArray) {
foreach($subDataArray as $value) {
$values[] = $value;
}
}
$valueString = implode(',', $values);
Edit: Added full solution..

How to get the keys in a PHP Array by position?

I have an array where I store key-value pair only when the value is not null. I'd like to know how to retrieve keys in the array?
<?php
$pArray = Array();
if(!is_null($params['Name']))
$pArray["Name"] = $params['Name'];
if(!is_null($params['Age']))
$pArray["Age"] = $params['Age'];
if(!is_null($params['Salary']))
$pArray["Salary"] = $params['Salary'];
if(count($pArray) > 0)
{
//Loop through the array and get the key on by one ...
}
?>
Thanks for helping
PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy:
foreach ($pArray as $key => $value)
{
print $key
}
//if you wanted to just pick the first key i would do this:
foreach ($pArray as $key => $value)
{
print $key;
break;
}
An alternative to this approach is to call reset() and then key():
reset($pArray);
$first_key = key($pArray);
It's essentially the same as what is happening in the foreach(), but according to this answer there is a little less overhead.
Why not just do:
foreach($pArray as $k=>$v){
echo $k . ' - ' . $v . '<br>';
}
And you will be able to see the keys and their values at that point
array_keys function will return all the keys of an array.
To obtain the array keys:
$keys = array_keys($pArray);
To obtain the 1st key:
$key = $keys[0];
Reference : array_keys()

Convert a string to an array in PHP

I have an array like such:
array('some_key' => 'some_value');
I would like to take that and transform it to, this should be done programatically
array('some_key' => array('some_value'));
This should be rather simple to do but the only think I can find is answers on string split and explode, to explode strings into arrays. I thought PHP, like other languages, had something called to_array or toArray.
I am assuming this is super easy to do?
If you're just doing the one array element, it's as simple as:
$newarray['some_key'] = array($sourcearray['some_key']);
Otherwise if your source array will have multiple entries, you can do it in a loop:
foreach($sourcearray AS $key => $value) {
$newarray[$key] = array($value);
}
Something as simple as $value = array($value) should work:
foreach ($array as &$value) {
$value = array($value);
}
unset($value); //Remove the reference to the array value
If you prefer to do it without references:
foreach ($array as $key => $value) {
$array[$key] = array($value);
}
You can try like this
<?php
$arr=array('some_key' => 'some_value');
foreach($arr as $k=>$v)
{
$newarr[$k] = array($v);
}
var_dump($newarr);

php - how do I display items from an array with their values

I have this array:
Array ( [#LFC] => 1 [#cafc] => 2 [#SkySports] => 1)
How do i display it like this on a page? (preferably in value descending order as below):
\#cafc (2), #LFC (1), #SkySports (1)
Thanks
First, sort the array
arsort($arrayName);
Next, iterate througth the array keys and values.
foreach($arrayName as $key => $value)
{
echo "$key ($value),";
}
Try using arsort to sort by descending value and then looping through the array, printing key/value pairs, as follows:
arsort($original_array);
foreach($original_array as $k => $v) {
echo $k.'('.$v.')';
}
if i got your question right, use a foreach loop in combination with arsort:
arsort($array);
foreach($array as $k => $v) {
printf('%s (%s)',
htmlspecialchars($k),
htmlspecialchars($v));
}
arsort($array);
$output = array();
foreach($array as $k => $v) {
$output[] = "$k ($v)";
}
print implode(", ", $output);
this will sort the array in reverse order, then create a new array with the data formatted the way you like, then implodes the output into a string separated by commas. The other answers so far will leave a dangling comma.

Categories