Getting values from a just created array - php

I have this function that creates an array of values:
function getPostInfo($query, $fields, $type, $limit, $since, $until, $lang, $stopwords, $identifier) {
$url = file_get_contents('https://graph.facebook.com/search?q='.spaces($query).'&fields='.$fields.'&limit='.$limit.'&until='.$until);
$j = json_decode($url);
foreach($j->data as $v) {
if ($v->type == $type) {
$author_id = $v->from->id;
$original_id = $v->id;
$post_url = getPostUrl($original_id, $author_id);
//$description = stopWords($v->message);
$description = $v->message;
$pub_date = $v->created_time;
$post[] = array(
'author_id' => $author_id,
'orginal_id' => $original_id,
'post_url' => $post_url,
'descritpion' => $description,
'pub_date' => $pub_date
);
}
}
return $post;
}
When I call this function like this:
$post = getPostInfo($query, $fields, $type, $limit, $since, $until, $lang, $stopwords, $identifier);
echo var_dump($post);
The array returns correctly.
But If I try to search for a specific value of the array like this:
echo var_dump($post['author_id']);
it always returns NULL.
What is wrong in my code?
Thank you for the help.

I believe if you change
$post[] = array(
to
$post = array(
it should fix the issue.
Can you display the result of your var_dump($post)?

The assignment in the function is wrong. You need to use this code (strip the [] parentesys)
$post = array(
'author_id' => $author_id,
'orginal_id' => $original_id,
'post_url' => $post_url,
'descritpion' => $description,
'pub_date' => $pub_date
);
or access the index you need by
$post[0]['author_id']
In this situation you should rely on var_dump or var_export to investigate on how your data structure is layed down. I prefer the second one as is output is similar to
the code needed to obtain the data and it is easier to find errors.
In the manual, you will see that var_dump returns void and if you try to echo its result you will not obtain what expected
echo var_dump($post['author_id']);
strip the echo and you will get fine with you output (use var_export or ob_start if you need to get a string with the output).
EDIT
As in the comment, the $post variable is an array of arrays, the above notes are still valid as you need to access the various author_id index prefixing the index of the array containing it. If you need to get all the id of the authors in a place then you can resort to array map:
$authors = array_map(function($x){return $x['author_id'];},$post);
If you where was trying to obtains something else you should better explain what the expected result was.

Like Eineki says you're trying to access an element of the array that doesn't exists. If you do a var_dump on the $post variable like this:
var_dump($post);
You should see that the $post array is actually a numerical array starting at [0] and each item includes a sub-array containing your data.
What you've created is a two dimensional array, an array of arrays, one array for each item in your $j->data array.
You can iterate through the array like this:
foreach ($post as $key => $value)
{
var_dump($value);
var_dump($value['author_id'];
}

Let's make this really fun and easy.
function getPostInfo($query, $fields, $type, $limit, $since, $until, $lang, $stopwords, $identifier) {
//your code
}
}
return (object)$post;
}
then when you access your returned object it's just
$post->author_id;
this is just for fun but it works well. Converts an array into a standard object. :)
ok let's get serious ;)
Initialize the array before the foreach statement ($posts = array()), then assign the variables to the array keys ($post['key'] = $value) then assign each set of array keys to the array ($posts[] = $post). I hope this helps.
function getPostInfo($query, $fields, $type, $limit, $since, $until, $lang, $stopwords, $identifier) {
$url = file_get_contents('https://graph.facebook.com/search?q='.spaces($query).'&fields='.$fields.'&limit='.$limit.'&until='.$until);
$j = json_decode($url);
$posts = array(); //initialize array here
foreach($j->data as $v) {
if ($v->type == $type) {
//create variables
$author_id = $v->from->id;
$original_id = $v->id;
$post_url = getPostUrl($original_id, $author_id);
//$description = stopWords($v->message);
$description = $v->message;
$pub_date = $v->created_time;
//asign values to array keys
$post['author_id'] = $author_id;
$post['orginal_id'] = $original_id;
$post['post_url'] = $post_url;
$post['descritpion']= $description;
$post['pub_date'] = $pub_date;
//asign $post to the $posts array to create an array of $post(s)
$posts[] = $post;
}
}
return $posts;
}
I think this might help accomplish what you want.
the following code is the reference used. It is from the examples from the Array section in the PHP manual.
<?php
// This:
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
$b = array('a', 'b', 'c');
// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Related

array with all my loops inside

i have this wordpress loop and i want to build a loop with all the variables...my problem my $array_data only stores the last loop and not all... how can i store all the loops in my $array_data array ?
foreach($adicionados as $post) :
$nome = simple_fields_values('pname1');
$im = simple_fields_values('ftotop');
$cp=$adicionados ;
$imatop = $im;
$data=get_sub_field('wallet_data');
$evento=get_sub_field('wallet_evento');
$obs=get_sub_field('wallet_obs');
$numeros_horas = get_sub_field('Wallet_n_horas');
$valor_horas = get_sub_field('wallet_valorh');
$evento = get_sub_field('wallet_evento');
$horarios = get_sub_field('wallet_horario');
$props=get_sub_field('wallet_props');
$total_parcial = $valor_horas * $numeros_horas."€";
$ii = wp_get_attachment_image($imatop[0]);
$array_valores['promotora'] []= get_the_ID();
$array_valores['valor'][]=$total_parcial;
$nomeid=get_the_ID($nome);
$array_data = array(
'foto' => $im,
'data' => $data,
'nome' => $nome,
'evento' => $evento,
'horario' => $horario,
'numero_horas' => $numero_horas,
'valor_horas' => $valor_horas,
'valor_parcial' => $total_parcial,
'obs' => $obs
);
You're seeing the last loop data because every time it loops it's storing different data. Which is similar to the following code:
$foo = 'one';
$foo = 'two'; // replaces 'one' with 'two'
$foo = 'three'; // replaces 'two' with 'three'
echo $foo; // outputs only 'three'
You need a two dimensional array here. An array of arrays.
Traditionally, you would make an index $i and store each loop's data with array_data[$i], exactly the essence of for( $i = 0; $i < count($adicionados); $i++).
But as mentioned in the comment, $array_data[] does that for you (although not as fast).

How do I insert a multidimensional array into another array in a loop?

I have this code:
$postList = array();
foreach($post as $blue)
{
$text = $string;
$url = trim(url);
$newPost = array( "ID" => $counter,
"Text" => $text,
"url" => $url );
$postList = array_merge($postList, $newPost);
$counter += 1;
}
This code does not work and what I find into the postList array is the last post item, not the list.
How do I insert all the items into the array?
Thanks in advance
try this
$postList = array();
$counter = 0;
foreach($post as $blue)
{
$text = $string;
$url = trim(url);
$newPost = array( "ID" => $counter,
"Text" => $text,
"url" => $url);
$postList[] = $newPost;
$counter += 1;
}
Save creating an extra variable try:
$postList = array();
foreach($post as $blue)
{
$text = $string;
$url = trim(url);
$postList[] = array( "ID" => $counter,
"Text" => $text,
"url" => $url );
$counter += 1;
}
In Object Oriented programming languages there is push method in the Array object. So it's something like this.
array.push(element);
This means push element at the end of the array. In PHP there is also push method, but it's static function, PHP libraries are like that. So you do something like this:
$persons = Array();
$person = Array('id' => 1, 'name' => 'my name');
array_push($persons, $person);
or
$array[] = $element;
The first one is more explicit and you'll understand better what it does. You should read more about data structures in PHP.

Get the sub array in a bidimensional array having a particular key/value pair

I have a large PHP array, similar to:
$list = array(
array(
'id' = '3243'
'link' = 'fruits'
'lev' = '1'
),
array(
'id' = '6546'
'link' = 'apple'
'lev' = '2'
),
array(
'id' = '9348'
'link' = 'orange'
'lev' = '2'
)
)
I want to get the sub-array which contains a particular id.
Currently I use the following code:
$id = '3243'
foreach ($list as $link) {
if (in_array($id, $link)) {
$result = $link;
}
}
It works but I hope there is a better way of doing this.
You can
write $link['id']==$id instead of in_array($id, $link) whitch will be less expensive.
add a break; instruction after $result = $link; to avoid useless loops
While this answer wouldn't have worked when the question was asked, there's quite an easy way to solve this dilemma now.
You can do the following in PHP 5.5:
$newList = array_combine(array_column($list,'id'),$list);
And the following will then be true:
$newList[3243] = array(
'id' = '3243';
'link' = 'fruits'; etc...
The simplest way in PHP 5.4 and above is a combination of array_filter and the use language construct in its callback function:
function subarray_element($arr, $id_key, $id_val = NULL) {
return current(array_filter(
$arr,
function ($subarr) use($id_key, $id_val) {
if(array_key_exists($id_key, $subarr))
return $subarr[$id_key] == $id_val;
}
));
}
var_export(subarray_element($list, 'id', '3243')); // returns:
// array (
// 'id' => '9348',
// 'link' => 'orange',
// 'lev' => '2',
// )
current just returns the first element of the filtered array.
A few more online 3v4l examples of getting different sub-arrays from OP's $list.

adding element to array

I have an array that looks like this:
array
0 =>
array
'title' => string 'Ireland - Wikipedia, the free encyclopedia'
'url' => string 'http://en.wikipedia.org/wiki/Ireland'
1 =>
array
'title' => string 'Ireland's home for accommodation, activities.'
'url' => string 'http://www.ireland.com/'
that I want to add a score of 0 to each element. I thought this simple foreach loop would do the trick but...well....it doesn't :/
public function setScore($result)
{
foreach($result as $key)
{
$key = array('title', 'url', 'score' => 0);
}
return $result;
}
Can someone help me out?
Thanks
foreach works on a copy of the array. You can modify $key all you want, it's not going to reflect on the original array.
You can use $key by reference though, then it'll work as expected:
foreach ($result as &$value) {
$value['score'] = 0;
}
Manual entry: http://php.net/manual/en/control-structures.foreach.php
You create a new array here and do nothing with it:
foreach($result as $key){
$key = array('title', 'url', 'score' => 0);
}
What you want to do is to modify a reference to existing one:
foreach($result as &$key){ # Note the '&' here
$key['score'] = 0;
}
Although deceze is right, you can also do this using array_walk(), like this:
array_walk( $result, function( &$el) { $el['score'] = 0; });
Here's an example of how to accomplish this.
$array = array( array( 'title' => "Ireland - Wikipedia, the free encyclopedia", 'url' => "http://en.wikipedia.org/wiki/Ireland"), array( 'title' => "Ireland's home for accommodation, activities.", 'url' => "http://www.ireland.com/" ) );
function setScore( $result )
{
foreach( $result as &$element )
{
$element['score'] = 0;
}
return $result;
}
$array = setScore( $array );
print_r( $array );
You could also do:
function setScore( &$result )
{...}
and then just:
setScore( $array );

PHP Api - Results/Array question

I have been looking around for PHP tutorials and I found a very detailed one that have been useful to me.
But now, I have a question. The results showed by the API are stored into a $results array. This is the code (for instance):
$fetch = mysql_fetch_row($go);
$return = Array($fetch[0],$fetch[1]);
$results = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
My question is.. I want to display the last 10 news.. how do I do this? On normal PHP / mySQL it can be done as:
while($var = mysql_fetch_array($table)) {
echo "do something"
}
How can I make it so the $results can print multiple results?
I have tried like:
while($var = mysql_fetch_array($table)) {
$results = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
}
But this only shows me one result. If I change the $results .= Array(...) it gives error.
What can I do?
Thanks!
Edit
My function to read it doesn't read when I put it the suggested way:
function write(XMLWriter $xml, $data){
foreach($data as $key => $value){
if(is_array($value)){
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
write($xml, $results);
$results[] = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
That should do it.
If you are familiar with arrays, this is the equivalent of an array_push();
array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:
<?php
$array[] = $var;
?>
Use [] to add elements to an array:
$results = array();
while($var = mysql_fetch_array($table)) {
$results[] = Array(
'news' => Array (
'id' => $var[0],
'title' => $var[1]
));
}
}
You can then loop through the $results array. It's not an optimal structure but you should get the hang of it with this.

Categories