Push an array within an array - php

I created a function called "keyword_query()" which gets a single string and runs a query with this variable on an API - then the API returns an array (which is defined global so it's changed outside the function too).
The second function "keyword_query_array()" should run the "keyword_query()" more than once, and push to a new array (which is global too) and get an array of several arrays. This function gets a variable of an array of keywords. The function gets the array and navigates through the array without any problem.
Please notice the comments in the code:
<?php
// Runs the query "Research Key" on a keyword and get App ids, names, ect'.
function keyword_query($keyword){
global $research_key_array, $keyword;
// Add the keyword to the "Research Key" query:
$research_key_query = "https://example.com/api/banana/ajax/kaka?term=$keyword&country=US&auth_token=666";
// Create a stream for Json. That's how the code knows what to expect to get.
$context_opts = array(
'http' => array(
'method' => "GET",
'header' => "Accepts: application/json\r\n"
)
);
$context = stream_context_create($context_opts);
// Get the Json
$research_key_json = file_get_contents($research_key_query, false, $context);
// Turn Json to a PHP array
$research_key_array = json_decode($research_key_json, true);
//var_dump($research_key_array);
//print_r($research_key_array);
return $research_key_array;
}
// Runs the keyword_query() function on an array of keywords.
function keyword_query_array($keyword_array){
global $array_of_key_queries;
// Get the last array cell
$last_array_cell = count($keyword_array);
// Navigate through the array
for ($i=0; $i<=$last_array_cell ; $i++) {
//echo $keyword_array[$i]; ****works!
// Error here: Notice: Undefined offset: 3 in C:\wamp\www\PHPExcel\api_fun.php on line 51
array_push( $array_of_key_queries, keyword_query($keyword_array[$i]) );
}
var_dump($array_of_key_queries);
}
But when I get to this line:
array_push( $array_of_key_queries, keyword_query($keyword_array[$i]) ); I get an error of:
Notice: Undefined offset: 3 in C:\wamp\www\PHPExcel\api_fun.php on line 51
with this var_dump:
array (size=4)
0 =>
array (size=1)
'keyword' =>
array (size=0)
empty
1 =>
array (size=1)
'keyword' =>
array (size=0)
empty
2 =>
array (size=1)
'keyword' =>
array (size=0)
empty
3 =>
array (size=1)
'keyword' =>
array (size=0)
empty
What is the right way to push an array within an array like this case?

I changed global $research_key_array, $keyword; from the first function to global $research_key_array;
Works great now!
Thanks #Adelphia !

Related

Extract just the strings from an array_column array return

I've got told many times, if there is a new question even on the same code to just create a new thread so here I am. Thanks to the guys for helping me with the previous question.
I have the following code:
/* Return an array of _octopus_ids */
$offices = array_map(
function($post) {
return array(
'id' => get_post_meta($post->ID, '_octopus_id', true),
);
},
$query->posts
);
/* Dump out all the multi-dimensional arrays */
var_dump($offices);
$test = array_column($offices, 'id');
var_dump($test);
var_dump($offices) dumps the following:
array (size=10)
0 =>
array (size=1)
'id' => string '1382' (length=4)
1 =>
array (size=1)
'id' => string '1330' (length=4)
var_dump($test) dumps the following:
array (size=10)
0 => string '1382' (length=4)
1 => string '1330' (length=4)
Problem:
How can I use the following code:
$results = $octopus->get_all('employees/' . $test; which results in an Notice: Array to string conversion error.
I want to be able to make a results call such as this $results = $octopus->get_all('employees/1382'); - So I want just the numeric string of $test to be appended to the end of employees/
If I hardcode the 1382 after employees/, I get the following result:
object(stdClass)[1325]
public 'id' => int 1382
What's the proper way to array of strings into just strings?

Set array value to a value from the same array on creation PHP

I'm trying to see if you can assign an array value during creation to a value in the same array.
If I'm declaring and initializing an array like this:
$this->array = array(...);
Can I do something like this?
$this->array = array
(
'value1' => 'hello',
'value2' => $this->array['value1'],
);
I've tried it already and I get back
Notice: Undefined index: value1 in /Sites/website/config.php on line 329
I've gotten around this problem already but now out of interest I want to see if theres actually a way to do this.
It has to be during creation and declared like above, not through
$array['value1'] = 'foo';
$array['value2'] = $array['value1'];
or
$common = 'foo';
$array = array('value1' => $common, 'value2' => $common);
Is this technically impossible or is there any way?
I don't think it's possible. The array has to be parsed before it can be assigned, so at the time $this->array['value1'] is being calculated, $this->array is still null.
Basically, $this->array['value1'] cannot be be accessed before $this->array['value2'] is set, which needs to access $this->array['value1'], which cannot be accessed before . . .
The reason you're getting Notice: Undefined index: value1 in /Sites/website/config.php on line 329 is because when you're defining your array the value you're trying to access has not yet been defined because you haven't reached the end of the initial function.
In the following code:
$this->array = array
( //this is the start of the array
'value1' => 'hello',
'value2' => $this->array['value1'],
); //this is the end of the array statement.
The array is not defined until you reach the end of the statement.
The reason the other methods work is because you're using multiple steps to access an already existing variable.
I think that is not possible, assign the element when the array starts
you can set as false and before the action that set the value as your code.
example :
$common = 'foo';
$array = array(
'value1' => $common,
'value2' => $common
);
or you can use the function array_combine

Array element returning null in laravel-4

I'm trying to get records from a table using a given ID and I want to store specific columns into another array but I'm getting null every time I var_dump() my array.
My code:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$getOrder[] = array(
array($ordersInWaypoints),
array(Order::where('id', '=', $ordersInWaypoints)->get()->lists('tracking_id')),
array(Order::where('id', '=', $ordersInWaypoints)->get()->lists('shipper_ref_no'))
);
}
For those wondering where $ordersInWaypoint came from, I retrieved that from here:
$ordersInWaypoint = array();
ordersInWaypoint = Transaction::where('waypoint_id', "=", $firstWaypoint)->get()->lists('order_id');
Don't mind the $firstWaypoint since that is determined by user input.
Everytime I var_dump($getOrder); I get the following result set:
array (size=1)
0 =>
array (size=3)
0 =>
array (size=1)
0 => int 637
1 =>
array (size=1)
0 =>
array (size=1)
...
2 =>
array (size=1)
0 =>
array (size=1)
...
The first element is correct, but the rest return empty sets.
I think you're getting no value because those Order::where(...) return Eloquent objects, not just single values.
You could better try this way:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$order = Order::where('id', '=', $ordersInWaypoints)->get();
$getOrder[] = array(
array($ordersInWaypoints),
array($order->tracking_id),
array($order->shipper_ref_no)
);
}
Let me know if this fixes it ;)
Edit
It's even better if you don't use a multidimensional array as you need just these three values, so the final code becomes:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$order = Order::where('id', '=', $ordersInWaypoints)->get(); // create Eloquent object from query
$getOrder[] = array(
$ordersInWaypoints,
$order->tracking_id, // Calls column value as method from the Eloquent object
$order->shipper_ref_no // Same (you could also call it as an array,
); // in that case you would type $order['shipper_ref_no']
}

Use returned data from array

I get some data from a table
Data is returned into an array like this
Array ( [id_widget] => 11 [id_user] => 7 [active] => 1 )
Then I am trying to use this "id_widget" and "entryemail" to insert them into another table.
"newentry" comes from an input, but I don't know how to post the "id_widget"
This is my model function
public function addentry($data) {
$this->db->insert('entries', array(
'id_widget' => $data['id_widget'],
'entryemail' => $data['entryemail']
));
}
This is my controller function:
public function entercontest() {
$entry = array(
'id_widget' => $this->widget[0]['id_widget'],
'entryemail' => $_POST['entryemail']
);
$this->model->addentry($entry);
}
It works to insert "entryemail" if I comment id_widget line everywhere.
The error doesn't occur when getting the value from the array $data['id_widget']. The error occurs in the entercontent function because you're populating the array with an undefined value because $this->widget is undefined.
Make sure $this->widget is defined and has the data before using it.

Accessing an array inside of an array

When trying to access an array inside an array, only NULL is output.
My Code:
$aStats = array();
$aStats['hd'] = array();
$aStats['hd'][] = array
(
'dev' => $device,
'total' => $total,
'used' => $used,
'free' => $free,
'used_perc' => $used_perc,
'mount' => $folder
);
echo $aStats['hd']['free'];
When using json_encode, the values are displayed correctly:
die( json_encode( $aStats ) );
Where is my mistake?
Replace these lines:
$aStats['hd'] = array();
$aStats['hd'][] = array
With this:
$aStats['hd'] = array
You appear to be accessing your array ($aStats['hd']['free'];) as if the value of hd is an associated array, but using [] creates a new integer index in the array, and stores the value in that index. Joe Walker's answer shows what happens instead, that you have an associative array pointing to an indexed array pointing to another associative array, rather than the associative to associative array you suggest you're trying to use in your echo statement.
This is a practical tip that will let you find out where is the issue easly, all you need to do is:
var_dump($aStats);
This will output:
array (size=1)
'hd' =>
array (size=1)
0 =>
array (size=6)
'dev' => string 'SomeDevice' (length=10)
'total' => string '10000' (length=5)
'used' => boolean true
'free' => boolean false
'used_perc' => string 'none' (length=4)
'mount' => string '/some/directory/here/' (length=21)
Now you know you can access this element using
$aStats['hd'][0]['free'];
This will return null in your question because your variables are not yet initialized, but I guess you do have them initialized in your code, hope this helps.

Categories