I have a multidimensional array that I would like to loop through and print the values that are stored in the array. This is the end result I am looking to achieve
{ "lat": 52.4469601, "lon": -1.93685532},
{ "lat": 52.44332417, "lon": -1.9426918},
{ "lat": 52.43987106, "lon": -1.9329071}
How would I go about printing the values like this? Currently this is how I am printing the whole array:
$enc = 'NTIuNDQ2OTYwMSwtMS45MzY4NTUzMnw1Mi40NDMzMjQxNywtMS45NDI2OTE4fDUyLjQzOTg3MTA2LC0xLjkzMjkwNzF8NTIuNDQ1NDk1MywtMS45MjU4MjYwN3w';
$decoded = base64_decode($enc);
$trim = trim($decoded, '|');
$data = explode('|', $decoded);
$out = array();
$step = 0;
$last = count($data);
$last--;
foreach( $data as $key => $item ) {
foreach (explode(',', $item) as $value) {
$out[$key][] = $value;
}
}
echo "<pre>";
print_r( $out );
echo "</pre>";
And the output looks like:
Array
(
[0] => Array
(
[0] => 52.4469601
[1] => -1.93685532
)
[1] => Array
(
[0] => 52.44332417
[1] => -1.9426918
)
[2] => Array
(
[0] => 52.43987106
[1] => -1.9329071
)
[3] => Array
(
[0] => 52.4454953
[1] => -1.92582607
)
)
If your data is exported always with "lat" and "lon" pairs then you can do this:
foreach( $data as $key => $item ) {
$lat = true;
foreach (explode(',', $item) as $value) {
if($lat == true){
$out[$key]["lat"] = $value;
$lat = false;
} else {
$out[$key]["lon"] = $value;
}
}
}
An other way to do it using a stream approach:
$enc = 'NTIuNDQ2OTYwMSwtMS45MzY4NTUzMnw1Mi40NDMzMjQxNywtMS45NDI2OTE4fDUyLjQzOTg3MTA2LC0xLjkzMjkwNzF8NTIuNDQ1NDk1MywtMS45MjU4MjYwN3w';
$handle = fopen("data:text/plain;base64,$enc", 'r');
$res = [];
while ( false !== $rec = stream_get_line($handle, 0, '|') ) {
$res[] = array_combine(['lat', 'lon'], str_getcsv($rec));
}
echo json_encode($res);
$enc = 'NTIuNDQ2OTYwMSwtMS45MzY4NTUzMnw1Mi40NDMzMjQxNywtMS45NDI2OTE4fDUyLjQzOTg3MTA2LC0xLjkzMjkwNzF8NTIuNDQ1NDk1MywtMS45MjU4MjYwN3w';
$decodedArr = explode('|', base64_decode($enc));
$latLong = [];
foreach ($decodedArr as $latLongStr) {
if (!$latLongStr) {
continue;
}
$temp = explode(',', $latLongStr);
$latLong[] = ['lat' => $temp[0], 'lon' => $temp[1]];
}
echo json_encode($latLong);
Output
[{"lat":"52.4469601","lon":"-1.93685532"},{"lat":"52.44332417","lon":"-1.9426918"},{"lat":"52.43987106","lon":"-1.9329071"},{"lat":"52.4454953","lon":"-1.92582607"}]
Related
I have string1 variable:
$string1 = category=123&code=456&type=type111&type=type222
How to create an array from a string that has a multiple occurances of the string1 variable?
Array(
array(
[category] => 123
[code] => 456
[type] => type111
),
array(
[category] => 123
[code] => 456
[type] => type222
)
)
Here is the solution, a bit messy, but works:
<?php
$string = "category=123&code=456&type=type111&type=type222";
$repeated_key = 'type';
$variable = explode('&', $string);
$data_o = array();
foreach ($variable as $key0 => $value0) {
$subvariable = explode('=', $value0);
if($subvariable[0] == $repeated_key){
continue;
}
$data_o[$subvariable[0]] = $subvariable[1];
}
$i=0;
foreach ($variable as $key1 => $value1) {
$subvariable = explode('=', $value1);
if($subvariable[0] != $repeated_key){
continue;
}
$data_t = array();
$data_t['type'] = $subvariable[1];
$data[] = array_merge($data_o,$data_t);
$i++;
}
echo "<pre>";
print_r($data);
exit;
?>
I'm trying below code to get the value as ou=grp1 from
dn: uid=john,ou=grp1,ou=people,dc=site,dc=com , but not understanding how to retrieve.
here is the code:
<?php
function pairstr2Arr ($str, $separator='=', $delim=',') {
$elems = explode($delim, $str);
foreach( $elems as $elem => $val ) {
$val = trim($val);
$nameVal[] = explode($separator, $val);
$arr[trim(strtolower($nameVal[$elem][0]))] = trim($nameVal[$elem][1]);
}
return $arr;
}
// Example usage:
$string = 'uid=john,ou=grp1,ou=people,dc=site,dc=com';
$array = pairstr2Arr($string);
echo '<pre>';
print_r($array);
echo '</pre>';
?>
output:
<pre>Array
(
[uid] => john
[ou] => people //here I want to get output ou=grp1,how?
[dc] => com
)
</pre>
find output here: https://ideone.com/rE6eaH
Because of ou and dc might have multiple values, you should store those values in array. Thanks to that you can have easy access to data. Check out this code:
<?php
function pairstr2Arr ($str, $separator='=', $delim=',') {
$elems = explode($delim, $str);
$arr = array();
foreach( $elems as $elem => $val ) {
$val = trim($val);
$tempArray = explode($separator, $val);
if(!isset($arr[trim($tempArray[0])]))
$arr[trim($tempArray[0])] = '';
$arr[trim($tempArray[0])] .= $tempArray[1].';';
}
foreach($arr as $key => $value)
{
$explodedValue = explode(';', $value);
if(count($explodedValue) > 2)
{
$arr[$key] = $explodedValue;
unset($arr[$key][count($explodedValue) - 1]);
}
else
$arr[$key] = substr($arr[$key], 0, -1);
}
return $arr;
}
// Example usage:
$string = 'uid=john,ou=grp1,ou=people,dc=site,dc=com';
$array = pairstr2Arr($string);
echo '<pre>';
print_r($array);
echo '</pre>';
?>
Result is:
Array
(
[uid] => john
[ou] => Array
(
[0] => grp1
[1] => people
)
[dc] => Array
(
[0] => site
[1] => com
)
)
I'm trying to group airlines with relations into single chains.
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
)
[1] => Array
(
[0] => Alitalia
[1] => Lufthansa
)
[2] => Array
(
[0] => Transaero
[1] => United
)
[3] => Array
(
[0] => United
[1] => Alitalia
)
[4] => Array
(
[0] => Volotea
[1] => Iberia
)
[5] => Array
(
[0] => Transaero
[1] => Aeroflot
)
)
From that array I need to find connections between elements and combine it to groups. Expected results:
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
[3] => United
[4] => Alitalia
[5] => Lufthansa
)
[1] => Array
(
[0] => Volotea
[1] => Iberia
)
)
Can anyone help with that? I've tried a dozen of ways but still get no success.
The most closest way I've tried which works but not in all cases:
function array_searchRecursive($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && array_searchRecursive($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
foreach ($newarr as $key => $airlines)
{
foreach ($airlines as $lastkey => $airline)
{
$index = array_searchRecursive($airline,$newarr);
echo $airline.$index."\n";
if ($index !== false)
{
$newarr[$index] = array_merge($newarr[$index],$airlines);
$lastarr[] = $index;
}
}
}
But it doesn't match all values in array.
Recursive function will help you. You are welcome )
$arr = array(
array('Aeroflot','S7','Transaero'),
array('Alitalia','Lufthansa'),
array('Transaero','United'),
array('United','Alitalia'),
array('Volotea','Iberia'),
array('Transaero','Aeroflot')
);
function getConnections($arr,$curr_line_n=0,$num=0) {
for($i=0;$i<count($arr[$curr_line_n]);$i++) {
$cur_air_name = $arr[$curr_line_n][$i];
for($k=$curr_line_n+1; $k<count($arr); $k++) {
for($l=0;$l<count($arr[$k]);$l++) {
if ($arr[$k][$l]==$cur_air_name) {
$arr[$curr_line_n] = array_values(array_unique(array_merge($arr[$curr_line_n],$arr[$k])));
array_splice($arr,$k,1);
$num++;
$arr = getConnections($arr,$curr_line_n,$num);
}
}
}
}
$num++;
$curr_line_n++;
if ($curr_line_n!=count($arr)) {
$arr = getConnections($arr,$curr_line_n,$num);
}
return $arr;
}
print_r(getConnections($arr));
As per your example you are just grouping sub arrays by taking first sub array as reference. for example if you have any elements common in first sub array and in subsequent sub arrays then you combine them into one sub array.
<?php
$arr = array(
array('a', 'b', 'c', 'd'),
array('d', 't'),
array('t', 'f'),
array('k', 'o'),
array('p', 'z')
);
$arr_implode = array();
foreach ($arr as $key => $value) {
if (is_array($value)) {
$arr_implode[$key] = implode('', $value);
} else {
$arr_implode[$key] = $value;
}
}
$arr_key = array();
$result = array();
$count = count($arr_implode);
$tempj = 0;
for ($i = 0; $i <= $count; $i++) {
$flag = FALSE;
for ($j = ($i + 1); $j < $count; $j++) {
similar_text($arr_implode[$i], $arr_implode[$j], $percent);
if ($percent > 0) {
$result[] = array_merge($arr[$i],$arr[$j]);
break;
} else {
$result[] = $arr[$j];
break;
}
}
}
foreach($result as $key => $val){
$result[$key] = array_unique($val);
}
echo "<pre>";
print_r($result);
echo "</pre>";
?>
Try this code.
$arr = [
['Aeroflot', 'S7', 'Transaero'],
['Alitalia', 'Lufthansa'],
['Transaero', 'United'],
['United', 'Alitalia'],
['Volotea', 'Iberia'],
['Transaero', 'Aeroflot']
];
$hash = [];
$result = [];
foreach($arr as $set){
foreach($set as $el){
if(!$hash[$el]) $hash[$el] = [] ;
$hash[$el] = array_merge($hash[$el], $set);
}
}
function merge_connections(&$h, $key){
if(!$h[$key]) return [];
$data = [$key];
$rels = $h[$key];
unset($h[$key]);
foreach($rels as $rel){
if($rel==$key) continue;
$data = array_merge($data, merge_connections($h, $rel));
}
return $data;
}
foreach(array_keys($hash) as $company){
if(!$hash[$company]) continue;
array_push($result, merge_connections($hash, $company));
}
print_r($result);
Given the following input:
array('one/two/3',
'one/four/0/5',
'one/four/1/6',
'one/four/2/7',
'eight/nine/ten/11')
How can I convert it into this:
array(
'one': array(
'two': 3,
'four': array(5,6,7)
)
'eight': array(
'nine': (
'ten':11
)
}
)
$input = array ('one/two/3',
'one/four/0/5',
'one/four/1/6',
'one/four/2/7',
'eight/nine/ten/11');
$result = array ();
foreach ($input as $string) {
$data = array_reverse(explode('/', $string));
$tmp_array = array ();
foreach ($data as $val) {
if (empty($tmp_array)) {
$tmp_array = $val;
} else {
$tmp = $tmp_array;
$tmp_array = array ();
$tmp_array[$val] = $tmp;
}
}
$result = array_merge_recursive($result, $tmp_array);
}
echo "<pre>";
print_r($result);
echo "</pre>";
Output:
Array
(
[one] => Array
(
[two] => 3
[four] => Array
(
[0] => 5
[1] => 6
[2] => 7
)
)
[eight] => Array
(
[nine] => Array
(
[ten] => 11
)
)
)
It would be nice if we saw what you have tried.
$my_array = array('one/two/3',
'one/four/0/5',
'one/four/1/6',
'one/four/2/7',
'eight/nine/ten/11');
$result= array();
foreach ($my_array as $val) {
$ref = & $result;
foreach (explode("/", $val) as $val) {
if (!isset($ref[$val])) {
$ref[$val] = array();
}
$ref = & $ref[$val];
}
$ref = $val;
}
var_dump($result);
How do you convert an array in PHP that looks like this:
Array (
[2] => B.eot
[3] => B.ttf
[4] => CarnevaleeFreakshow.ttf
[5] => CarnevaleeFreakshow.eot
[6] => TRASHED.ttf
[7] => sub.ttf
)
To look like this:
Array(
[B]=>array(
[0] => B.eot
[1] => B.ttf
)
[CarnevaleeFreakshow]=>array(
[0] => CarnevaleeFreakshow.ttf
[1] => CarnevaleeFreakshow.eot
)
[TRASHED]=>array(
[0] => TRASHED.ttf
)
[sub]=>array(
[0] => sub.ttf
)
)
Is there a name for doing something like this?
the data is being retrieved from a
scandir
array.
<?php
$data = array (
2 => 'B.eot',
3 => 'B.ttf',
4 => 'CarnevaleeFreakshow.ttf',
5 => 'CarnevaleeFreakshow.eot',
6 => 'TRASHED.ttf',
7 => 'sub.ttf'
);
$new_data = array();
foreach ( $data as $value ) {
$tmp = explode( '.', $value );
$ext = '';
if ( $tmp[1] ) $ext = '.' . $tmp[1];
$new_data[ $tmp[0] ][] = $tmp[0] . $ext;
}
print_r( $new_data );
?>
Here is an example.
It can be written shorter, but I think this is the most instructive.
$ARRraw = array (
"B.eot",
"B.ttf",
"CarnevaleeFreakshow.ttf",
"CarnevaleeFreakshow.eot",
"TRASHED.ttf",
"sub.ttf"
) ;
$sorted = array();
foreach($ARRraw as $one){
$firstPoint = strpos($one,".");
// No point? then skip.
if (!($firstPoint === false)){
// Get the part before the point.
$myKey = substr($one,0,$firstPoint);
$sorted[$myKey][] = $one;
}
}
Is there a name for doing something like this?
Nope. Anyway, it should be rather simple using a loop:
<?php
$newArray = array( );
foreach( $originalArray as $fontfile ) {
$newArray[basename( $font )][] = $fontfile;
}
echo '<pre>' . print_r( $newArray, true );
To what i know there is no 'simple' method of doing this.
you could build a function to handle it though.
function convertArray($array) {
$newArray = array();
foreach( $array as $item ) {
$newArray[basename($item)] = $item;
}
return $newArray;
}
That should do what your looking for.
Try it:
function subdiv(array $arr) {
$res = array();
foreach($arr as $val) {
$tmp = explode('.', $val);
if(!isset($res[$tmp[0]]))
$res[$tmp[0]] = array();
$res[$tmp[0]][] = $val;
} return $res;
}
use with:
$res = subdiv($array);
var_dump($res);