I'm trying to figure out someone else's code that doesn't work at my company any more.
I have a variable set $row[9]. The data is from a CSV file that the php parses. The var_dump looks like this
When I try to put $row[9] into an array by doing this $school = explode(",", $row[9])
var_dump($school) outputs this.
print_r($school) outputs this.
print_r
Shouldn't $school look something like this below?
[0] => array(1) {[0] => string(8) "2/3-AM"}
[1] => array(1) {[0] => string(8) "2/3-AM"}
[2] => array(1) {[0] => string(8) "1/2B-AM"}
Let me know if I need to add any other information.
It appears if the first screenshot is all values that $row[9] takes. As if it is iterating over a list, $row[9] has multiple values between the beginning and end of execution. It is not an array of all of those values; it is each of those values individually.
If you were to explode(',', $each_value), then each value will become array( [0] => $each_value ), since each value does not contain a comma.
Given you anticipated output, it seems you expect $row[9] to be an array of those strings, when it is simply a string that changes value over time.
Related
I am getting a Json respond with :
$response = curl_exec($rest);
$json = json_decode($response, true);
I manage to get its values(strings) with :
$foundUserId=$json['results'][0]['userId'];
$foundName=$json['results'][0]['name'];
$foundPhoneNum=$json['results'][0]['phoneNumber'];
But the last value- phoneNumber, is array of strings .
If i try then to loop over it i get nothing(although the array is there in the Json)
foreach ($foundPhoneNum as &$value)
{
print_r($value);
}
What am i doing wrong ?
EDIT :
The json:
Array ( [results] => Array ( [0] => Array ( [action] => message [createdAt] => 2015-11-21T09:36:33.620Z [deviceId] => E18DDFEC-C3C9 [name] => me [objectId] => klMchCkIDi [phoneNumber] => ["xx665542","xxx9446"] [state] => 1 [updatedAt] => 2015-11-22T08:24:46.948Z [userId] => 433011AC-228A-4931-8700-4D050FA18FC1 ) ) )
You might have json as a string inside json. That's why after json_decode() you still have json inside phoneNumber. You have 2 options:
Decode phoneNumber like
$foundPhoneNum=json_decode($json['results'][0]['phoneNumber']);
Build proper initial json. Instead of
{"phoneNumber": "[\"xx665542\",\"xxx9446\"]"}
should be
{"phoneNumber": ["xx665542","xxx9446"]}
There's a couple of ways to debug situations like this as mentioned in the comments; print_r() and var_dump().
var_dump(), although harder to read the first few times, is my favourite because it tells you the data types of each value in the array. This will confirm whether or not the expected string is indeed an array.
An example from the var_dump() documentation:
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
And the output is;
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
As you can see it shows array, int and string as the data types.
You might also like to install the Xdebug extension for PHP which dumps more useful error messages and tracebacks. Again harder to read the first few times, but well worth it!
foreach ($foundPhoneNum as $value)
{
print_r($value);
}
There was an extra & before $value. Try this.
I have to insert some data from an excel document into the database.
The data has been saved as .csv and then added into an array through PHP.
The data look like:
Column A Column B Column C
100 200 100
50 10 100
200 200 100
30 10 300
Then I use this to separate each columns (within a foreach loop)
list( $columnA, $columnB) = explode( ',', $values[0] );
$columnA= array($columnA);
print_r($columnA);
The above code prints the values of each column.
So I'm trying to find a way to remove duplicates from each column and then from each row (no matter what the column name is). I want to remove duplicates from the whole document. For the data I posted for example I just need the values 100,200,50,10,30,300 (only the unique values from the whole doc).
UPDATE:
What the original array (the one I've created by using for loop and passing all data from .CSV file) shows:
Array ( [0] => G2100,100%,,,,,,,,,200,0.24,77,51,2,47, )
Array ( [0] => G2101,100%,,,,,,,,,200,0.24,77,42,15,43, )
Array ( [0] => G2102,30%,,,,,,,,,200,0.24,77,38,25,37, )
So by using the list function I mentioned before I split all columns and get the values for each column. THEN if i print $columnB array for example it shows this:
Array ( [0] => 100%) Array ( [0] => 100%) Array ( [0] => 30%)
and so on. When I use unique_array it does nothing.
$columnB = array_unique($columnB, SORT_REGULAR);
I tried to use array_map but it doesn't work either.
Any help would be much appreciated.
I don't understand why does array_unique not works in your case, because actually it solves the problem:
<?php
$columnA = array(50,50,200,10);
$columnB = array(100,50,200,100);
$columnC = array(150,50,250);
$merged = array_merge($columnA, $columnB, $columnC);
$result = array_unique($merged);
var_dump($result);
?>
And output is:
array(6) {
[0]=>
int(50)
[2]=>
int(200)
[3]=>
int(10)
[4]=>
int(100)
[8]=>
int(150)
[10]=>
int(250)
}
This is an trivial example, but if you can manage that your inputs are like arrays above, then you can use array_unique to have only unique values...
EDIT 1:
To remove % sign from string just use rtrim where is needed:
$string = '100%';
$trimmed = (int)rtrim($string,'%');//make it int(or float if you like)
var_dump($trimmed);
EDIT 2:
Related to looping through arrays:
//I suppose this
//Array ( [0] => 100%) Array ( [0] => 100%) Array ( [0] => 30%)
//maps to this
$columnA = array(
0=>array('100%'),
1=>array('100%'),
2=>array('30%')
);
//go through every element
$temp = array();
foreach($columnA as $subArray){
//in this case when we know that there is only one element in the array we can do next:
$temp[] = $subArray[0];
}
$result = array_unique($temp);
echo "<pre>";
var_dump($result);
echo "</pre>";
And this would be the output:
array(2) {
[0]=>
string(4) "100%"
[2]=>
string(3) "30%"
}
I have an array:
Array
(
[0] => 20140929102023_taxonomies.zip
[1] => 20140915175317_taxonomies.zip
[2] => 20140804112307_taxonomies.zip
[3] => 20141002162349_taxonomies.zip
)
I'd like order this array by first 14 characters of strings, that represents a date.
I'd like an array like this:
Array
(
[0] => 20140804112307_taxonomies.zip
[1] => 20140915175317_taxonomies.zip
[2] => 20140929102023_taxonomies.zip
[3] => 20141002162349_taxonomies.zip
)
Thanks.
The sort() function with the natural sorting algorithm should give you the result you are looking for. It's as simple as this.
sort($array, SORT_NATURAL);
This will updat the existing $array variable, you do not need to store the return of the sort function. It simply returns true or falseon success and failure.
The sort function will update the keys as well, if for some reason you need to maintain the keys, and just update the order, you can use asort().
asort($array, SORT_NATURAL);
PHP has tons of ways to sort arrays, you can find the manual for that here.
There is no need to use natural sorting algorithms. A normal sort() would produce the effect you desire, as it will compare each string "starting from the left". For example "20141002162349_taxonomies.zip" is bigger than "20140929102023_taxonomies" because the fifth character (the first digit of the month) is 1 in the first and 0 in the second (and 1 > 0, even in a string - comparison works with ASCII code points).
So:
<?php
$array = array('20141002162349_taxonomies.zip', '20140929102023_taxonomies.zip', '20140804112307_taxonomies.zip', '20140915175317_taxonomies.zip');
sort($array);
var_dump($array);
Result:
array(4) {
[0]=>
string(29) "20140804112307_taxonomies.zip"
[1]=>
string(29) "20140915175317_taxonomies.zip"
[2]=>
string(29) "20140929102023_taxonomies.zip"
[3]=>
string(29) "20141002162349_taxonomies.zip"
}
I'm very new to php and I've been spending quite some type understanding how to pass arguments from Python to php and conversely.
I now know how to pass single variables, but I am still stuck and can't seem to find an answer to this one:
Php calls a Python script (that part works) that returns a list of strings. I'd like to process this list in php.
When I try:
print mylist
in myscript.py, and then :
$result = exec('python myscript.py')
it looks like php understands $result as a single string (which I agree makes sense).
I understand that maybe json can help or that I somehow need to use a dictionary instead of a list in python. However I can't figure out how exactly.
If anyone can help, it will be much appreciated! Thanks!
For instance:
myscript.py
import json
D = {'foo':1, 'baz': 2}
print json.dumps(D)
myscript.php
<?php
$result = json_decode(exec('python myscript.py'), true);
echo $result['foo'];
You're using stdin / stdout to transfer the data between the programs, that means you'll have to encode your structure somehow in order to let your receiving program parse the elements.
The simplest thing would be to have python output something like a comma separated list
Adam,Barry,Cain
and use
$result = explode(exec('python myscript.py'));
on the php side to turn your string data back into an array.
If the data is unpredictable (might contain commas) or more structured (more than just a simple list) then you should go for something like json as suggested by Krab.
Apparently your question was misleading. Was redirected here thinking this a solution for converting python lists to php array.
Posting a naive solution for ones wanting to convert lists to php array.
// Sample python list
$data = '[["1","2","3","4"],["11","12","13","14"],["21","22","23","24"]]';
// Removing the outer list brackets
$data = substr($data,1,-1);
$myArr = array();
// Will get a 3 dimensional array, one dimension for each list
$myArr =explode('],', $data);
// Removing last list bracket for the last dimension
if(count($myArr)>1)
$myArr[count($myArr)-1] = substr($myArr[count($myArr)-1],0,-1);
// Removing first last bracket for each dimenion and breaking it down further
foreach ($myArr as $key => $value) {
$value = substr($value,1);
$myArr[$key] = array();
$myArr[$key] = explode(',',$value);
}
//Output
Array
(
[0] => Array
(
[0] => "1"
[1] => "2"
[2] => "3"
[3] => "4"
)
[1] => Array
(
[0] => "11"
[1] => "12"
[2] => "13"
[3] => "14"
)
[2] => Array
(
[0] => "21"
[1] => "22"
[2] => "23"
[3] => "24"
)
)
$str = "[u'element1', u'element2', 'element3']";
$str = str_replace( array("u'", "[", "]"), array("'", ""), $str );
$strToPHPArray = str_getcsv($str, ",", "'");
print_r( $strToPHPArray );
Outputs
Array
(
[0] => element1
[1] => element2
[2] => element3
)
What is the difference between var_dump, var_export and print_r ?
var_dump is for debugging purposes. var_dump always prints the result.
// var_dump(array('', false, 42, array('42')));
array(4) {
[0]=> string(0) ""
[1]=> bool(false)
[2]=> int(42)
[3]=> array(1) {[0]=>string(2) "42")}
}
print_r is for debugging purposes, too, but does not include the member's type. It's a good idea to use if you know the types of elements in your array, but can be misleading otherwise. print_r by default prints the result, but allows returning as string instead by using the optional $return parameter.
Array (
[0] =>
[1] =>
[2] => 42
[3] => Array ([0] => 42)
)
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script. Note that var_export can not handle reference cycles/recursive arrays, whereas var_dump and print_r check for these. var_export by default prints the result, but allows returning as string instead by using the optional $return parameter.
array (
0 => '',
1 => false,
2 => 42,
3 => array (0 => '42',),
)
Personally, I think var_export is the best compromise of concise and precise.
var_dump and var_export relate like this (from the manual)
var_export() gets structured
information about the given variable.
It is similar to var_dump() with one
exception: the returned representation
is valid PHP code.
They differ from print_r that var_dump exports more information, like the datatype and the size of the elements.