I have the following array extracted from a CSV file.
$line = Array (
[0] => First
[1] => Last
[2] => 102338100053
[3] => https://url.com/SKnuDbowTveUsHXwMAnixg?t=kIMVJtQ
[4] => 48a9ee0d-ba30-4ef7-94b0-75f03009e2c6
[5] => 1436.75
[6] => 21.55125
)
I am trying to get the value of [2]
I extract it like this
$number2 = $line[2];
This is fine. I get the following response. 102338100053
When I try to extract the first 6 numbers from the variable using
$Identifier = substr($number2 ,0,6)
I only get 2 numbers: 10
if I use 12
$siteIdentifier = substr($number2 ,0,12)
I get: 102338
I found this confusing so I checked the variable with urlencode
echo urlencode($number2);
This is what I received: %001%000%002%003%003%008%001%000%000%000%005%003%00
I need to get just the number and I dont know what to do to get it, as I am searching for this in a database and its not finding it?
Can someone please assist?
You may try using gettype() which gives you the datatype of your variables. Then the rest must be pretty simple to understand. I used $i<6 condition because you've mentioned you want only the first six integers.
$i= 0;
foreach($line as $key => $value){
if(gettype($value) == integer){
if($i<6){
$ints[$i] = $value;
$i++;
}
}
}
Related
I am using an api to show a list of times but struggling to display them in using foreach
Here is how the data is shown:
stdClass Object
(
[id] => 2507525
[snapshotTimes] => Array
(
[0] => 2020-10-02T04:04:41+00:00
[1] => 2020-10-03T03:22:29+00:00
[2] => 2020-10-04T03:06:43+00:00
[3] => 2020-10-04T21:18:11+00:00
[4] => 2020-10-06T03:07:12+00:00
[5] => 2020-10-07T03:21:31+00:00
[6] => 2020-10-10T03:43:00+00:00
[7] => 2020-10-17T02:58:49+00:00
[8] => 2020-10-19T02:57:35+00:00
[9] => 2020-10-23T03:08:28+00:00
[10] => 2020-10-26T04:02:51+00:00
[11] => 2020-10-27T04:33:19+00:00
)
)
Code:
$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");
foreach ($domainArray as $arr) {
$Time = $arr->$domainArray->snapshotTimes;
echo " TIME: $Time<br>";
}
But it doesn't seem to echo anything at all? Where am I going wrong?
Your code shows;
$Time = $arr->$domainArray->snapshotTimes;
Here you're tying to access a property called domainArray on the array given by the foreach(). No need to do that since your already using the foreach() to loop over the data;
$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");
// For each item in the 'snapshotTimes' array
foreach ($domainArray->snapshotTimes ?? [] as $time) {
echo " TIME: {$time}<br>";
}
Try it online!
Note: Using the null coalescing operator (?? []) to ensure snapshotTimes exists in the data.
Based on comments; the same solution but with array_reverse() to reverse the output.
foreach (array_reverse($domainArray->snapshotTimes) as $time) {
....
Try it online!
You are triying to print snapshotTimes but you created a loop for another thing. If you want to print snapshotTimes code will be like :
foreach($arr->$domainArray->snapshotTimes as $time){
echo $time."</br>";
}
snapshotTimes is an array, but you are treating it as if it was a string. you should probably run another inner foreach to cycle through all values within snapshotTimes . Check your PHP Error log.
Perhaps an example would help him #Martin?
Example:
$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");
foreach ($domainArray as $arr) {
if(is_array($arr->snapshotTimes) && count($arr->snapshotTimes) > 0 ){
$times = $arr->snapshotTimes;
foreach($times as $timeRow){
echo " TIME: ".$timeRow."<br>";
}
unset($times); //tidy up temp vars.
}
}
I underline the point that you need to check your PHP Error Log to help you diagnose these sort of structure issues.
Notes:
Your reference $arr->$domainArray->snapshotTimes within the foreach is incorrect, you're referencing both the foreach label as well as the source of the foreach label, which will result in an error.
PHP variables should start with a lower case letter.
If you don't need $domainArray => $arr for any other reason within the foreach loop, you can simplify the loop by looping the array rather than the container, as 0stone0 shows on their answer.
Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.
I am just trying to create PHP variables dynamically. below is the code I have tried.
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
while
$BrickTerritorys is
[1] => stdClass Object
(
[id] => 119
[TerritoryID] => HYD-2-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 40.00
[BPCode] => bp00066
[GroupCode] => CMD
)
[2] => stdClass Object
(
[id] => 36330
[TerritoryID] => HYD-1-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 60.00
[BPCode] => bp00066
[GroupCode] => CMD
)
When I print in the last, nothing gets printed. Any help is much appreciated, please.
Thanks in advance
${"T$index"} as well as ${"Weightage$index"}
you don't need the dot,or you can use ${'T' . $index}. look at the dot. it's not addition operation while it in "". following this code:
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
Try changing those lines like this:
${"T$index"}= $BrickTerritory->TerritoryID;
${"Weightage$index"} = $BrickTerritory->Weightage;
In your code ${"$T.$index"} $T is searching for variable, and you should get undefined variable $T, so you have to remove $ sign, if you want to have T1, T2 variables.
After that, ${"'Weightage'.$index"}, the apostrophes between Weightage means your variable will look like 'Weightage'.1, 'Weightage'.2.. and etc.
This can be done a few different ways without variable variables AND produce a completely dynamic outcome.
Here's one: (Demo)
$array = (array)$BrickTerritorys; // cast as array
$tids = array_column($array, 'TerritoryID'); // isolate column data
$was = array_column($array, 'Weightage'); // isolate column data
$merged = array_merge($tids, $was); // add 2nd array data after 1st array data
foreach ($merged as $i => $v) {
echo str_repeat('-', $i) , $v; // increase hyphens on each iteration starting from 0
}
Output: (notice, no hardcoded echo)
HYD-2-CMD-HYD-1-CMD--40.00---60.00
I'm new to php and have been using the community and answers here to really help me with a little project I'm working on so thank you all in advance for the help so far!
I am pulling a load of information held in a poorly formatted text file/feed, trimming the contents of special characters and then using str_replace to find other specific strings and replace them with commas(,) or semi-colons(;), in order to create a usable piece of text. I then want to search this text for certain keywords and return other parts of the text in it's place.
So far, I've managed to explode the text into a multidimensional array, but I can't work out how to search this array now, in order to pull out a specific piece of information. I'm essentially trying to build a searchable array that I can pull information from as and when the original feed updates. Here's a sample of the array as it stands at the moment:
Array
(
[0] => Array
(
[0] => 240
[1] => 1
[2] => euro
[3] => 2016-02-19 15:30:00
[4] => EUR
)
[1] => Array
(
[0] => 240
[1] => 3
[2] => euro2
[3] => 2016-02-19 15:00:00
[4] => EUR
)
[2] => Array
(
[0] => 1890
[1] => 9
[2] => uspb
[3] => 2016-02-17 22:59:00
[4] => USD
)
)
Essentially, I want to be able to write something that will search this array for say uspb (array 2, key 2) and if it is found, return the value held under another key. So if I want key 0, it will return 1890. If I want key 1 when searching for euro2 it will return "3".
I've looked through a ton of examples and nothing really fits what I'm after at the moment. Perhaps I'm looking at this the wrong way and using an array isn't the correct approach. Any advice would be greatly appreciated.
For reference, here's a copy of my code (slight redacted) so far.
<?php
$file=file_get_contents("http://www.example.com/feed/");
$trim=trim($file, "[]");
$find = array("{\"value\":\"", "\",\"date_utc\":\"", "\",\"currency\":\"");
$replace = array(",", ",", "");
$replaced = str_replace($find, $replace, $trim);
$ret = array_map (
function ($_) {return explode (',', $_);},
explode (';', $replaced)
);
print_r ($ret);
?>
As your array is multidimensional - you have to iterate over it to find the value you need:
foreach ($ret as $value) {
// the index you want to search is always `2`?
if ($value[2] == 'uspb2') {
echo $value[0];
break;
}
}
And moving to function:
function findMyValue(
$array,
$search_key,
$search_str,
$key
) {
foreach ($array as $v) {
if ($v[$search_key] == $search_str) {
return $v[$key];
}
}
return 'NOT_FOUND';
}
echo findMyValue($ret, 2, 'euro', 1); // outputs 3
echo findMyValue($ret, 2, 'uspb', 0); // outputs 1890
And as already noticed in comments - it's not a poorly formated text, it's JSON. You can get an array from JSON string simply with json_decode function:
$file=file_get_contents("http://www.example.com/feed/");
$ret = json_decode($file, true);
var_dump($ret);
I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.