PHP Break Apart Array Variables - php

I am extracting XML from a feed. There is a tag entitled:
<georss:point>34.234 -34.435</georss:point>
which contains two variables I am inserting into MySQL
When I run this code, the variable is 'array'. I then place an extract to break out the variables, unsure of next
$xmlString = str_replace('georss:point','point',$xmlString);
$xml = new SimpleXMLElement($xmlString);
$items = $xml->xpath('channel/item');
$closeItems = array();
foreach($items as $item)
{
$latlng = explode(' ',trim($item->point));
array(
'lat'=>$latlng[0],
'lng'=>$latlng[1]
);
$lat = array($latlng[0]);
$lng = array($latlng[1]);
echo $lat;
echo $lng;
}
When I place those echo statements (in the last two lines of code), the variables get echod to the screen. However when I place these varaibles outside of the array, the values do not get echod.
I am attempting to get these variables outside of the array, so that I can insert these variables into the database. I have tried extract on the varaiables, but this prints back to the screen as 'Array'... unsure of what I need to do to extract these variables from the array. Thanks,

Replace your foreach with a version like this...
$new_array = array();
foreach($items as $item)
{
$latlng = explode(' ',trim($item->point));
$new_array[] = array('lat'=>$latlng[0],'lng'=>$latlng[1]);
}
var_dump($new_array);
this should give you a array of your lat/long values.

Some observations.
1) you can register xpath namespaces instead of replacing in the string
2) array('lat'=>$latlng[0],'lng'=>$latlng[1]); does nothing. It is a dead store.
3) Instead of
$lat = array($latlng[0]);
$lng = array($latlng[1]);
echo $lat;
echo $lng;
You can do: echo $latlng[0].'-'.$latlng[1];
If you try to echo an array, you will always get Array.
Use a specific index to echo an individual element.
4) Alternatively you could use list to store the variables directly
list($lat, $long) = explode(' ',trim($item->point));
Edit
To insert multiple results into your database, store the results in an array:
$lat_long = array();
foreach($items as $item){
$lat_long[] = explode(' ', $item);
}
Then later iterate through this array and do your database insert.
foreach($lat_long as $point){
//do SQL injection prevention as well
//INSERT INTO your_table (`lat`, `long`) VALUES ($point[0], $point[1]);
}

I think this:
$lat = array($latlng[0]);
$lng = array($latlng[1]);
should be:
$lat = $latlng[0];
$lng = $latlng[1];

Obmitting the array(..) around $latlng[..] would do the trick, I think.
$lat = $latlng[0];
$lng = $latlng[1];

Related

Convert a string structured as a Multidimensional Array to array

I have this string:
array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));
Stored in $_POST['data']
The string Im receiving is via.load` function where the structure of the string is constructed like so.
I would like to convert it to a multidimensional array via php so I can loop through it easily
So far I`ve reached a workaround by modifying both the string and the method.
Now my string looks like this :
1,name1,1,0,|2,name2,0,1,|3,name3,0,1,|4,name4,1,1,|5,name5,1,0,|
And the method is this
$data2 = $_POST['data2']; /// get data
$data2 = substr_replace($data2 ,"", -2); // eliminate ,|
$data2 = $data2."|"; // add |
$one=explode("|",$data2); // create multidimensional array
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
I can keep this solution but I would like to know if there is another way of doing it as first requested
There is a better and simple way. You just need to use a foreach loop inside foreach loop.
$data = array(
array('1','name1','1','0'),
array('2','name2','0','1'),
array('3','name3','0','1'),
array('4','name4','1','1'),
array('5','name5','1','0')
);
foreach( $data as $d ) {
foreach( $d as $value ) {
echo $value;
echo '<br />';
}
}
You can check the online Demo
To parse your original string you can use eval()
$string = 'array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));';
eval('$array = '.$string);
But eval can/should be disabled on the server, because it comes with security issues.
What i would do is to use JSON, where you would POST the json encoding it with:
json_ecnode( $my_array );
and then decoding it:
$array = json_decode( $_POST['data'], true );

Removing beginning and end character from String without altering array

I'm running a query to display an array. After the array is displayed I'm using that in Google Maps so the array needs to read a specific way.
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
So my array has to read array', 'array', 'array because I echo the array into the address.
var addresses = ['<?php echo $namelist ?>'];
This is my code and it outputs 'array', 'array', 'array',
$resultsearch = $con->query("SELECT * FROM db") or die(mysqli_error());
$name = array();
while ($result = $resultsearch->fetch_object()) {
$name[] = $result->name;
$namelist = substr("'".implode($name)."', ", 0, -1);
If I change the 0, -1 to 1, -2 then I'm left with array' array' array' and so forth.
I literally need the remove 1 character from the end of string and 1 character at the beginning without altering the characters of the array.
Just to add that using implode(',', $name); did not display the ',' which is why I'm trying to find a work around.
Any ideas?
Your problems are:
You use implode(); in the wrong way: right is implode("', '",$names);
substr() will not work because of wrong use of implode().
Tip: Instead of using substr() just do rtrim('value',',');
To fix your code change it to this:
$name[] = "'{$result->name}'";
$namelist = implode(', ',$name);
or this
$name[] = $result->name;
$namelist = implode("', '",$name);
And this too:
var addresses = [<?php echo $namelist ?>];
to get proper javascript/json array data.
Also works:
var addresses = <?php echo json_encode($namelist); ?>;
But here you should not add ' single-quotes to the names when collecting into an array.
Have a nice day
I ended up with $namelist = "'".$result->name."'," and then echo $namelist;
My results were addresses and believe that implode(',', $name) wouldn't work because of the results.

In_array not working - compare two files

The code below is a simple version of what I am trying to do. The code will read in two files, see if there is a matching entry and, if there is, display the difference in the numbers for that item. But it isn't working. The first echo displays the word but the second echo is never reached. Would someone please explain what I am missing?
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Your $mainArry contains a single element: the string 'Albert,8'. It looks like you want to use it as an array (elements 'Albert' and '8') instead of a string.
You mention the code will read from two files, so you can 'explode' it to a real array, as you do with $arry. A simpler approach would be using str_getcsv() to parse the CSV string into $mainArry.
$inputString = 'Albert,8';
$mainArry = str_getcsv($inputString); // now $mainArry is ['Albert','8']
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Test it here.
You are attempting to compare the string Albert with Albert,8, so they won't match. If you want to check if the string contains the keyword, assuming your array has more than one element, you could use:
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
foreach ($mainArry as $comp) {
if (strstr($comp, $kword[0])) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
}
example: https://eval.in/728566
I don't recommend your way of working, but this is a solution, basically the process you apply to the $arry should also apply to the $mainArry you're trying to compare it to.
$mainArry = array('Albert,8');
$arry = array('Albert,12');
/***
NEW function below takes the valus out of the main array.
and sets them in their own array so they can be properly compared.
***/
foreach ($mainArry as $arrr){
$ma = explode(",",$arrr);
$names[] = $ma[0];
$values[] = $ma[1];
}
unset($arrr,$ma);
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
/// note var reference here is updated.
if (in_array($kword[0], $names)) {
echo '<br>line '.$kword[0]. ' has count of '.$kword[1] . '<br>';
}
}
Yeah, MarcM's answer above does the same thing in a neat single line, but I wanted to illustrate a little more under the hood operations of the value setting. :-/

Extract PHP variables from one line separated by comma

i'm storing data in a database column like this.
1920,1927,3772,6127,3671
and i want to extract this value to variable as many as they are.
$var1 = 1920
$var2= 1927
$var3= 3772
$var4= 6127
$var5= 3671
and automatically read any new value WHILE there is "," comma and add it to a new var
Try something like this :
$vars = '1920,1927,3772,6127,3671';
$array_vars = explode(",",$vars);
foreach($array_vars as $key => $value){
${'var' . $key} = $value;
}
echo $var1;
Use explode function
$values = "1920,1927,3772,6127,3671";
$split_to_var = explode(',', $values);
$var1 = $split_to_var[0] ; // first one
echo $var1; // Returns 1920
It's not a very good idea to store them like this, but you can do it with explode.
$ar = explode(',',$initial_var);
Now you have the $ar array with all values and you can access them as $ar[1], $ar[2] etc.
You can use explode. something like below
$str = '1920,1927,3772,6127,3671';
$arr = explode(',' , $str);
//var_dump($arr);
For accessing the values use foreach
foreach($arr as $val){
//echo $val;
}
or
$var1 = $arr[0];
$var2 = $arr[1];
$var3 = $arr[2];
$var4 = $arr[3];
$var5 = $arr[4];
It is bad relational database technique to store information in this way. Break it into a separate table with a foreign key. This will make querying a lot easier and you won't have to worry about breaking up the string.

PHP From string to two variables

In my db there is a table that have some values like this[string]
100/100
50/100
40/80
7/70
I need to change this values in
100%
50%
50%
10%
How can i do this using only PHP/mysql code?
EDIT:this is the code:
foreach ($html->find('div.stat') as $status_raw){
$status = $tag_pic_raw->src;
$status = mysql_real_escape_string($status);
$data->query("INSERT IGNORE INTO `tb` (`value`) VALUES ('".$status."')");
}
I have used a DOM inspector to get info from another site
Used explode() combined with some math.
$str = '40/80';
$vals = explode('/', $str);
$percent = (($vals[0] / $vals[1]) * 100).'%';
echo $percent;
use explode() to divide up the values and then math them.
foreach($array as $val) // assuming all the (##/##) values are in an array
{
$mathProblem = explode("/", $val);
echo (intval($mathProblem[0]) / intval($mathProblem[1]) * 100)."%<br />";
}
You can set up a function similar to this:
function math($one)
{
$new = explode("/", $one);
$math = $new[0] / $new[1];
$answer = $math * 100;
return $answer."%";
}
Then every time you need to query something, you can do it simply by doing this:
foreach ($results as $r)
{
echo math($r);
}
This just makes it (I think) tidier and easier to read.
Use explode() :Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter( / in this case).
$arr=array('80/100','50/100','40/80');
foreach($arr as $str){
$values = explode('/',$str);
echo ((int)$values[0]/(int)$values[1])*100.'%<br/>';
}

Categories