I Connect to a remote SSH device in Php.
I run a command that output is too long.
So I searched and understood I can save it via :
$my_array= explode("\n", $this->ssh->exec('some command'));
Its ok, Now I can display whole output via :
echo print_r($my_array);
Output is something like :
Array ( [0] => ath4_auth_mode=disabled [1] => wl_mac_deny= [2] => filter_dport_grp3= [3] => ses_script= [4] => http_redirect_port=3128 [5] => oet5_en=0 [6] => filter_dport_grp4= [7] => oet2_fragment=0 [8] =>
When I run :
echo count($my_array);
It displays me :
2200
So it is true, Now I wanna search for a specific text like name=,I want the value after equal in the array, I tried this :
$search_result = array_search("name=", $my_array);
But no chance, Even tried :
foreach($my_array as $cat) {
$cat = trim($cat);
if($cat == "name=") {
echo "hoola !";
} else {
echo ':-(';
}
Again no chance, How can I search for the name= and get the value after = ?
I suppose in your array value is not name= exactly. It can be name=something for example. In this case neither == nor in_array will find it. You need to use strpos:
foreach($my_array as $cat) {
$cat = trim($cat);
if(strpos($cat, "name=") === 0) {
echo "hoola !", $cat;
// add a break if value found so as not to search other elements
break;
} else {
echo ':-(';
}
}
I used === and 0 because name= must be in the beginning of your $cat.
Related
I need to print only one sub_title of first child(1955) array.
Here is some sample code (that works) to show what I mean.
$array = Array
(
[1955] => Array
(
[sub_title] => subtitle
[sub_content] => content
)
[1957] => Array
(
[sub_title] => subtitle
[sub_content] => conent
)
[1958] => Array
(
[sub_title] => subtitle
[sub_content] => conent
)
)
array_walk($array, function($item){
echo $item['sub_title'];
break;
});
As far as I understand your task, you need to get the first element of the array. Use reset(array $array) function to get the first element, than get the value.
So your code should look like $fistElement = reset($array); echo $firstElement['sub_titile'];
Please also read the documentation on array function and don't try to sew with a hammer
You should create a global boolean variable which acts as a flag
<?php
$walk_arr = [
0 => "A",
1 => "B",
3 => "D",
5 => "F",
];
global $stop_walk;
$stop_walk = false;
$walk_func = function(&$v, $k) {
global $stop_walk;
if ($k === 3) {
$stop_walk = true;
}
if ($stop_walk) {
return;
}
$v .= " changed";
};
unset($stop_walk);
array_walk($walk_arr, $walk_func);
print_r($walk_arr);
print $stop_walk;
See it in action: https://3v4l.org/6kceo
BTW: Can't you just output the first row?
echo $array[1995]['sub_title']
I'm working on a PHP function and getting this error I don't understand...
print_r($my_array); will output
Array (
[0] => Array (
[field_id_41] =>
)
)
but if I try to do
if ($my_array[0]['field_id_41'] == "some value")
I get the error
Undefined offset: 0
I've tried $my_array['0'] but that doesn't make a difference. I'm able to assign the value to another variable, and print that, but for some reason using it for the if statement breaks it.
I'm really not sure what's going on here... Any help appreciated.
EDIT: here's the actual loop I'm having trouble with
foreach($counsellors_result as $one_counsellor) {
$this_time_out_query = ee()->db->select('field_id_41')
->from('channel_data')
->where('entry_id', $one_counsellor['parent_id'])
->get();
$this_time_out = $this_time_out_query->result_array();
$time_out_status = $this_time_out['0']['field_id_41'];
if ($time_out_status != "Time Out") {
ee()->db->insert(
'relationships',
array(
'parent_id' => $entry_id,
'child_id' => $one_counsellor['parent_id'],
'field_id' => 111
)
);
}
}
try this way its help full
<?php
$this_time_out=array (0 => array ( 'field_id_41' =>""));
$time_out_status = $this_time_out[0]['field_id_41'];
if($time_out_status != ""){
echo $time_out_status;
}else{
echo "no any value<br><br>";
}
//print "no any value"
$this_time_out=array (0 => array ( 'field_id_41' =>"test"));
$time_out_status = $this_time_out[0]['field_id_41'];
if($time_out_status != ""){
echo $time_out_status;
}else{
echo "no any value";
}
//print "test"
Did you var_dump in every loop iteration? I can guess that you get array(array('field_id_41'=>'')) in the first iteration but null in the second iteration. When you look at the output you can't see var_dump(null).
Please try to dump it that way:
$i = 0;
foreach (...) {
//...
var_dump(array('i' => $i, 'var' => $time_out_status));
$i++;
//...
}
You'll probably see that in the second iteration you get:
array('i' => 1, 'var' => null)
I'm not sure if I've titled this correctly...
I have this array :
array (
'fu' => 'bar',
'baz' =>
array (
0 => 'bat',
),
)
And I can search it using :
echo array_search('bar', $myarray);
Which will return the key of bar, which is :
fu
But how do I search for the value of fu?
If I try :
echo array_search('fu', $myarray);
I get no results.
!!EDIT to show more code as requested!!
$data = '{fu:"bar",baz:["bat"]}';
$parsed = array();
parse_jsobj($data, $parsed);
Now if I use :
var_export($parsed);
I get :
array (
'fu' => 'bar',
'baz' =>
array (
0 => 'bat',
),
)
If I use this instead :
print_r($parsed);
I get :
Array ( [fu] => bar [baz] => Array ( [0] => bat ) )
And I'm trying to return the Value of fu like this :
echo array_search('fu', $parsed);
But I get no results.
Like wise if I try :
echo $parsed['fu'];
echo $parsed[0]->fu;
echo $parsed[0];
This function only seems to return the Key and won't return the Value. Maybe I'm looking for a different function?
The class I'm using is HERE
echo $myarray[array_search('bar', $myarray)];
I'm not sure why you'd want to do this though, as you already know the result of fu. I think it far more likely you actually want to do this:
echo $myarray['fu'];
edit:
Leaving the above for posterity. After the edit with more info, hopefully this will work:
$parsed2 = $parsed;
$parsed = array();
foreach($parsed2 as $key=>$value){
if(is_string($key) || is_numeric($key)) {
$parsed[$key] = $value;
} else {
$parsed["'".$key."'"] = $value;
}
}
unset($parsed2);
echo $parsed['fu'];
if that doesn't work, then I've no more ideas.
How can i add element to my array under a specific key?
This is my array output before i use foreach. As you can see, the error field is empty. I want to fill it out.
Array (
[0] => Array (
[transactionid] => 2223
[created] => 26-02-13 14:07:00
[cardid] => 10102609
[pricebefordiscount] => 68900
[error] =>
)
This is my foreach. As you can see i already tried to make this work by implementing $arrayname['index'] = $value;. But this does not work, nothing comes out when i spit out in a print_r. Why is this happening?
foreach ($samlet as $key)
{
if ($key['pricebefordiscount'] > '200000')
{
$samlet['error'] = "O/2000";
}
if ($key['cardid'] === '88888888')
{
$samlet['error'] = "Testscan";
}
}
This is the desired output:
Array (
[0] => Array (
[transactionid] => 2223
[created] => 26-02-13 14:07:00
[cardid] => 10102609
[pricebefordiscount] => 68900
[error] => "Testscan"
)
Change your foreach, so you have the indexes used in the "main" $samlet array:
foreach($samlet as $key => $array)
{
if ($array['cardid'] === '88888888')
{
$samlet[$key]['error'] = '0/2000';
}
}
And so on...
Try this :
foreach ($samlet as &$key){
if ($key['pricebefordiscount'] > '200000'){
$key['error'] = "O/2000";
}
if ($key['cardid'] === '88888888'){
$key['error'] = "Testscan";
}
}
According to PHP manual:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
So your code should looke like this:
<?php
foreach ($samlet as &$key)
{
if ($key['pricebefordiscount'] > '200000')
{
$key['error'] = "O/2000";
}
if ($key['cardid'] === '88888888')
{
$key['error'] = "Testscan";
}
}
TRY THIS
foreach ($samlet as $key=>$value)
{
if ($value['pricebefordiscount'] > '200000')
{
$samlet[$key]['error'] = "O/2000";
}
if ($value['cardid'] === '88888888')
{
$samlet[$key]['error'] = "Testscan";
}
}
I would like to learn a smart way to unpack nested array. For instance, i have an array variable $rma_data['status'] which looks like below;
[status] => Array
(
[0] => Array
(
[created] => 1233062304107
[statusId] => 5
[statusName] => Open
)
[1] => Array
(
[created] => 1233061910603
[statusId] => 2
[statusName] => New
)
[2] => Array
(
[created] => 1233061910603
[statusId] => 1
[statusName] => Created
)
)
I would like to store the Created timestamps and statusId into an variables based on the condition like: if we find out there is "Open" status exist, we will use Open instead of "New" and "Created" . If there is only New and Created, we will use New instead .
Current version of my way to do that:
for($i=0; $i<count($rma_data['status']); $i++)
{
switch($rma_data['status'][$i]['statusId'])
{
case 5:
case 2:
case 3:
}
Any ideas?
For small to medium scale, what you already have looks good.
My only suggestions would be to use additional variables, for example the count and to unroll some of the compact code to be more efficient and readable.
For example:
$total=count($rma_data['status']);
for($i=0; $i<$total; $i++){
$x=$rma_data['status'][$i];
if($x['statusName']=='Open'){ // Use your criteria
$t=$x['created'];
//...Do Work
}
}
If you're really depended on these three specific values of statusName, a more straightforward and readable way to go about it would be to create an indexed array of status types which you can test more easily.
For example:
$rma_statuses = array();
foreach ((array)$rma_data['status'] as $status) :
$rma_statuses[$status['statusName']] = array(
'created'=>$status['created'],
'id'=>$status['statusId']
);
endforeach;
$rma_stauts = $rma_statuses['open'] ?: ($rma_statuses['new'] ?: $rma_statuses['created']);
// Do something with $rma_stauts['created'] and $rma_stauts['id']
I do not quite understand a necessary condition but it can be like this will help:
$searched_status_id = null;
$searched_timestamp = null;
foreach ($rma_data['status'] as $id => $status) {
if ((!$searched_timestamp && !$searchуd_status_id) ||
($status['statusName'] == 'New' || $status['statusName'] == 'Open')) {
$searched_timestamp = $status['created'];
$searched_status_id = $status['statusId'];
}
if ($status['statusName'] == 'Open') {
break;
}
}
if(is_array($rma_data['status'])){
//assuming there are only three values inside it
//case1
$open = ( $rma_data['status'][0]['statusName'] == 'Open' ||
$rma_data['status'][1]['statusName'] == 'Open' ||
$rma_data['status'][2]['statusName'] == 'Open');
//case2
$new = (!$open &&
($rma_data['status'][0]['statusName'] == 'New' ||
$rma_data['status'][1]['statusName'] == 'New' ||
$rma_data['status'][2]['statusName'] == 'New' ));
if($open){
echo 'open';
}elseif($new){
echo 'New';
}else{
echo 'None';
}
}
Second:
foreach($rma_data['status'] as $key => $val){
$statusName = $val['statusName'];
$newarray[$statusName] = $val;
}
echo '<pre>';
print_r($newarray);
if(array_key_exists('Open', $newarray)){
$created = $newarray['Open']['created'];
$statusId = $newarray['Open']['statusId'];
echo 'Open';
}
elseif(array_key_exists('New', $newarray)){
$created = $newarray['New']['created'];
$statusId = $newarray['New']['statusId'];
echo 'New';
}else{
echo "None";
}