explode associative array in php and adding two fields in the array - php

output of form:
Array (
[0] => (19.979802102871425,73.78671169281006)
[1] => (19.97978382724978,73.78682289971039)
[2] => (19.979765551626006,73.78697712672874)
)
expect output:
Array (
[0] =>
[lag]=>19.979802102871425,
[long]=>73.78671169281006,
[1] => [lag]=>19.97978382724978,
[long]=>73.78682289971039
[2] => [lag]=>19.979765551626006,
[long]=>73.78697712672874
)
following code working is not given me desired output as i am unaware of adding two associate element in array
foreach($_POST['textbox'] as $value):
$value = str_replace(array('(',')'), '',$value);
foreach (explode(',', $value) as $topic) :
list($name, $items) =$topic;
///stuck up here
}
$test[] = explode(',', $value);
endforeach;
endforeach;
could please suggest the changes in the code as i reffered following links but the expected out is different from mine.thanks in advance
php-explode-and-put-into-array
explode-function

You can try this -
foreach($your_array As &$array) {
$temp = explode(',', str_replace(array('(', ')'), '', $array)); // replace the ()s & explode the value
$array = array('lat' => $temp[0], 'long' => $temp[1]); // store with keys
}

Try this :
foreach($array as $value){
list($lat,$lng) = explode(',',trim(trim($value,')'),'('));
$out[] = array( 'lat' => $lat , 'lng' => $lng);
}
var_dump($out);

Related

Array keep on repeating in foreach

I have an array holding string in it's values, I am finding underscore in each value breaking it and inserting it into new array, It's doing all right but only for first array in second array it repeats first array also.
For Example
$someArraVal[] = 'abc_xyz__vr1_vr2';
$someArraVal[] = 'emf_ccc__vr2_vr3';
First I am getting everything after double underscore then exploding them with underscore and trying to have array like below
Array
(
[0] => Array
(
[0] => vr1
[1] => vr2
)
[1] => Array
(
[2] => vr3
[3] => vr4
)
)
but I am getting
Array
(
[0] => Array
(
[0] => vr1
[1] => vr2
)
[1] => Array
(
[0] => vr1
[1] => vr2
[2] => vr3
[3] => vr4
)
)
CODE
$someArraVal[] = 'abc_xyz__vr1_vr2';
$someArraVal[] = 'emf_ccc__vr3_vr4';
$arr1 = [];
$arr2 = [];
$xmx = [];
foreach ($someArraVal as $key => $value) {
$afterunderscore = substr($value, strpos($value, "__") + 1);
// $addPipe = str_replace("_","|",$afterunderscore);
$abc = substr($afterunderscore, 1);
$arr1 = explode('_',$abc);
foreach ($arr1 as $k => $v) {
$arr2[] = $v;
}
$xmx[] = $arr2;
}
printR($xmx);
You need to empty the array $arr2 at the start of foreach loop.
.
.
.
foreach ($someArraVal as $key => $value) {
$arr2 = []; //Empty the $arr2 at begining of the loop
.
.
.
}
You never reset $arr2 so you append more data each iteration.
You can add $arr2 = [] right after the foreach.
Better solution will be to do:
foreach ($someArraVal as $key => $value) {
$afterunderscore = substr($value, strpos($value, "__") + 1);
$xmx[] = explode('_',substr($afterunderscore, 1));
}
Live example: 3v4l
Second array keeps repeating because you are looping inside the array which will take all the values.
<?php
$someArraVal[] = 'abc_xyz__vr1_vr2';
$someArraVal[] = 'emf_ccc__vr3_vr4';
$arr1 = [];
foreach ($someArraVal as $key => $value) {
$afterunderscore = substr($value, strpos($value, "__") + 1);
$abc = substr($afterunderscore, 1);
$arr1[] = explode('_',$abc);
}
echo '<pre>';
print_r($arr1);
echo '</pre>';
Please check : https://prnt.sc/oitez2
Another technique using a single iterated function call...
Code: (Demo)
$someArraVal[] = 'abc_xyz__vr1_vr2';
$someArraVal[] = 'emf_ccc__vr2_vr3';
foreach ($someArraVal as $value) {
$xmx[] = preg_split('~(?:[^_]+_)*_~', $value, 0, PREG_SPLIT_NO_EMPTY);
}
print_r($xmx);
Output:
Array
(
[0] => Array
(
[0] => vr1
[1] => vr2
)
[1] => Array
(
[0] => vr2
[1] => vr3
)
)
The pattern consumes the undesired substrings and treats them as delimiters. This leaves you with only the substrings that you want.
If the idea of regex scares you, here's a non-regex solution with just two calls per iteration:
foreach ($someArraVal as $value) {
$xmx[] = array_slice(explode('_', $value, 5), -2);
}
// same result array

Convert a one dimensional array to two dimensional array

I have an array, whose structure is basically like this:
array('id,"1"', 'name,"abcd"', 'age,"30"')
I want to convert it into a two dimensional array, which has each element as key -> value:
array(array(id,1),array(name,abcd),array(age,30))
Any advice would be appreciated!
I tried this code:
foreach ($datatest as $lines => $value){
$tok = explode(',',$value);
$arrayoutput[$tok[0]][$tok[1]] = $value;
}
but it didn't work.
Assuming you want to remove all quotation marks as per your question:
$oldArray = array('id,"1"', 'name,"abcd"', 'age,"30"')
$newArray = array();
foreach ($oldArray as $value) {
$value = str_replace(array('"',"'"), '', $value);
$parts = explode(',', $value);
$newArray[] = $parts;
}
You can do something like this:
$a = array('id,"1"', 'name,"abcd"', 'age,"30"');
$b = array();
foreach($a as $first_array)
{
$temp = explode("," $first_array);
$b[$temp[0]] = $b[$temp[1]];
}
$AR = array('id,"1"', 'name,"abcd"', 'age,"30"');
$val = array();
foreach ($AR as $aa){
$val[] = array($aa);
}
print_r($val);
Output:
Array ( [0] => Array ( [0] => id,"1" ) [1] => Array ( [0] => name,"abcd" ) [2] => Array ( [0] => age,"30" ) )
With array_map function:
$arr = ['id,"1"', 'name,"abcd"', 'age,"30"'];
$result = array_map(function($v){
list($k,$v) = explode(',', $v);
return [$k => $v];
}, $arr);
print_r($result);
The output:
Array
(
[0] => Array
(
[id] => "1"
)
[1] => Array
(
[name] => "abcd"
)
[2] => Array
(
[age] => "30"
)
)

How to convert multi-dimensional array into single array using PHP?

After implementing database queries, I am getting the multi-dimensional array below.
Two Dimensional Array
Array
(
[0] => Array
(
[t1] => test1
)
[1] => Array
(
[t2] => test2
)
[2] => Array
(
[t3] => test3
)
[3] => Array
(
[t4] => test4
)
[4] => Array
(
[t5] => test5
)
)
but I want to convert it to a single dimensional array, like the format below:
One Dimensional Array
Array (
t1 => test1
t2 => test2
t3 => test3
t4 => test4
t5 => test5
)
How can I do this?
I think you can use array_reduce() function.
For example:
$multi= array(0 => array('t1' => 'test1'),1 => array('t2' => 'test2'),2 => array('t3' => 'test3'),3 => array('t4' => 'test4'));
$single= array_reduce($multi, 'array_merge', array());
print_r($single); //Outputs the reduced aray
You can use as follows :
$newArray = array();
foreach($arrayData as $key => $value) {
foreach($value as $key2 => $value2) {
$newArray[$key2] = $value2;
}
}
Where $arrayData is your DB data array and $newArray will be the result.
Assuming that source array is array of arrays and it has no the same keys:
<?php
$src = [
['t1'=>'test1'],
['t2'=>'test2'],
['t3'=>'test3'],
['t4'=>'test4'],
['t5'=>'test5'],
];
$result = call_user_func_array('array_merge', $src);
result via var_dump():
array(5) {
["t1"]=>
string(5) "test1"
["t2"]=>
string(5) "test2"
["t3"]=>
string(5) "test3"
["t4"]=>
string(5) "test4"
["t5"]=>
string(5) "test5"
}
You can use array_reduce() to change values of array. In callback get key of item using key() and select first item using reset().
$newArr = array_reduce($oldArr, function($carry, $item){
$carry[key($item)] = reset($item);
return $carry;
});
Check result in demo
Try this function,
function custom_function($input_array)
{
$output_array = array();
for ($i = 0; $i < count($input_array); $i++) {
for ($j = 0; $j < count($input_array[$i]); $j++) {
$output_array[key($input_array[$i])] = $input_array[$i][key($input_array[$i])];
}
}
return $output_array;
}
$arr = custom_function($arr);
print_r($arr);
Give it a try, it will work.
You can use this
<?php
$temp = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result_array = array();
foreach ($temp as $val) {
foreach ($val as $key => $inner_val) {
$result_array[$key] = $inner_val;
}
}
print_r($result_array);
?>
// Multidimensional array
$arrdata = Array(
'0' => Array(
't1' => 'test1'
) ,
'1' => Array(
't2' => 'test2'
) ,
'2' => Array(
't3' => 'test3'
)
);
// Convert to a single array
$data = array();
foreach($arrdata as $key => $value) {
foreach($value as $key1 => $value1) {
$data[$key1] = $value1;
}
}
echo $data;
Try array map function.
$singleDimensionArray = array_map('current',$multiDimensionArray);
You can use this if you don't care about keeping the correct array keys
function flattenA(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
print_r(flattenA($arr));
// Output
Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
[4] => test5
)
Otherwise
function flattenB(array $array) {
$return = array();
array_walk_recursive($array, function($v,$k) use (&$return) { $return[$k] = $v; });
return $return;
}
print_r(flattenB($arr));
// Output
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
Check both on Sandbox
From answer on similar question
For your specific case, I would use array_reduce where I set the initial value with an empty array
array_reduce($arr, function($last, $row) {
return $last + $row;
}, array());
AFTER PHP 7.4
array_reduce($arr, fn ($last, $row) => $last + $row, []);
Result :
[
't1' => 'test1',
't2' => 'test2',
't3' => 'test3',
't4' => 'test4',
't5' => 'test5'
]
Hey #Karan Adhikari Simple like below one:
<?php
$arr1 = array(array("t1" => "test1"), array("t2" => "test2"), array("t3" => "test3"), array("t4" => "test4"), array("t5" => "test5"));
echo "<pre>";
print_r($arr1);//before
$arr2 = array();
foreach($arr1 as $val){
$arr2 = array_merge($arr2, $val);
}
echo "<pre>";
print_r($arr2); // after you get your answer
Please try this function:
function array_merging($multi_array) {
if (is_array($multi_array)) {
$new_arr = array();
foreach ($multi_array as $key => $value) {
if (is_array($value)) {
$new_arr = array_merge($new_arr, array_merging($value));
}
else {
$new_arr[$key] = $value;
}
}
return $new_arr;
}
else {
return false;
}
}
Use this function:
$your_multi_arr = array(array(array('t1'=>'test1'),array('t2'=>'test2'),array('t3'=>'test3'),array('t4'=>'test4')));
$arr1 = array_merging($your_multi_arr);
echo "<pre>";
print_r($arr1);
Hope, this may be useful for you.
You can try traversing the array using PHP while list and each. I took sample code from PHP website the second example you can check it here
$arr = [['t1' => 'test1'],['t2' => 'test2'],['t3' => 'test3'],['t4' => 'test4'],['t5' => 'test5']];
$output = [];
while (list($key, $val) = each($arr)) {
while (list($k, $v) = each($val)) {
$output[$k] = $v;
}
}
print_r($output);
Output created is
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
You can test it on your own in this Sandbox example.
This will do the trick
$array = array_column($array, 't1');
Note: This function array_column introduced in PHP 5.5 so it won't work in earlier versions.
traverse the array and save the key value, Live Demo here.
<?php
$array = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result = [];
array_walk($array, function($value) use(&$result){
foreach($value as $k => $v)
{
$result[$k] = $v;
}
});
var_dump($result);
`$result = "Query"; $key_value = array();`
foreach ($result as $key => $value) {
$key_value[$key['']] = $value[''];
}
//for checking //echo "<pre>" ; print_r($key_value) ; exit;
return $key_value;
pls fill $key['name given in sql query for field'] and $value['name given in sql query for field'] (both are same)
this works for me
$result = [];
foreach($excelEmails as $arr)
{
foreach ($arr as $item){
$result = array_merge($result , $item);
}
}
dd($result);
i would recomment my way to convert all double-dimensional array to single-dimensional array.
<?php
$single_Array = array();
//example array
$array = array(
array('t1' => 'test1'),
array('t2' => 'test2'),
array('t3' => 'test3'),
array('t4' => 'test4'),
array('t5' => 'test5'));
$size = sizeof($array);
//loop to fill the new single-dimensional array
for($count = 0; $count<sizeof($array);$count++)
{
//take the key of multi-dim array
$second_cell = key($array[$count]);
//set the value into the new array
$single_array[$count] = $array[$count][$second_cell];
}
//see the results
var_dump($single_array);
?>
with this script we can take keys and values to create new single-dimensional array.I hope that i was helpfull to you.
you can see the example here: Array Convert Demo

Get only Numeric values from Array in PHP

I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}

Joining array values into string

I have a PHP array with multiple objects. I'm trying to join values from a certain key into one string separated by commas. Output from var_dump:
Array
(
[0] => stdClass Object
(
[tag_id] => 111
[tag_name] => thing 1
[tag_link] => url_1
)
[1] => stdClass Object
(
[tag_id] => 663
[tag_name] => thing 2
[tag_link] => url_2
)
)
The string needs to be $string = 'thing 1,thing 2'. I tried using a foreach loop, but I'm completely stuck. Could anyone help out?
The above answer is a little light, maybe run it as a foreach loop instead.
$names = array();
foreach ($array as $k => $v) {
$names[] = $v->tag_name;
}
$string = implode(',', $names);
$output = '';
foreach($test as $t){
$output .= $t->tag_name . ',';
}
$output = substr($output, 0, -1);
echo $output;
Try as this
$string = $array[0]->tag_name.','.$array[1]->tag_name;
For other elements
$string = '';
foreach($array as $object) $string.=$object->tag_name.',';
$string = substr($string,0,-1);
Use something like this:
implode(',', array_map(function ($el) {
return $el->tag_name;
}, $array));

Categories