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).
Related
I`ve got the following array:
$myarray = array(
2 => array(
'id' => '2',
'parent_id' => '1',
),
4 => array(
'id' => '4',
'parent_id' => '2',
),
3 => array(
'id' => '3',
'parent_id' => '1',
),
1 => array(
'id' => '1',
'parent_id' => '0',
)
);
and the goal is to have the following output:
1
1.2
1.2.4
1.3
The problem is that I need to do that without recursion. Here is some kind of an answer but the guys there are building tree while I need to have strings. I tried to use some kind of $basestring variable in order to know where am I, but still it did not work without recursion. Any ideas how to do that?
Thank you
UPD My first attempt was the following:
foreach($myarray as $k=>$value){
if($value['parent_id'] == 0){
$string = '1';
$id = $value['id'];
$newarr[0] = $string;
$basestring = $string.'.';
}elseif($value['parent_id'] == 1){
$string = $basestring.$value['id'];
$id = $value['id'];
$newarr[$id] = $string;
}elseif($value['one'] == 2){
$string = $basestring.$value['parent_id'].'.'.$value['id'];
$id = $value['id'];
$newarr[$id] = $string;
}elseif($value['parent_id'] == 3){
$string = $basestring.$value['parent_id'].'.'.$value['id'];
$id = $value['id'];
$newarr[$id] = $string;
}elseif($value['parent_id'] == 4){
$string = $basestring.$value['parent_id'].'.'.$value['id'];
$id = $value['id'];
$newarr[$id] = $string;
}//etc...
}
}
but obviously it failed due to non-scalability. I need to code somehow the iteration from child to parent here
An iterative solution could work something like this:
foreach ($myarray as $x) {
$temp = $x;
$string = [];
while (true) {
$string[] = $temp['id']; // add current level id
if (!isset($myarray[$temp['parent_id']])) break; // break if no more parents
$temp = $myarray[$temp['parent_id']]; // replace temp with parent
}
$strings[] = implode('.', array_reverse($string));
// array_reverse is needed because you've added the levels from bottom to top
}
Basically for each element of the array, create a temporary copy, then find its parents by key and set the temporary copy to the parent until no more parents are found. Add the ids into an array as you go and build the string from the array when you get to the end.
This assumes your array is valid, in that it does not contain circular references (e.g. one level being its own ancestor). To prevent an infinite loop if this did happen, you could increment a variable within the while loop and break if it reached some reasonable limit.
I have an array which contains information on posts I have made.
$DexArray = array(
array(
'url' => "http://i.imgur.com/ObXLdd6C.jpg",
'headline' => "Dronningens Nytårstale",
'subline' => "Tallene bag talen og årets spilforslag",
'href' => "nytaarstale.php",
'postedby' => "kris",
'postedurl' => "https://www.facebook.com/dataanalyticsdk",
'dato' => "21. december, 2014"
),
array(
'url' => "http://i.imgur.com/sxddhOe.jpg",
'headline' => "Endless Jewelry",
'subline' => "Are there really endless possibilities?",
'href' => "endless.php",
'postedby' => "Nikolaj Thulstrup",
'postedurl' => "kris",
'dato' => "10. december, 2014"
),
It is stored in a multidimensional associate array. I am trying to retrieve a random 'href' value in the array and store it as a variable.
I have tried using the array_rand function but it doesn't seem to work.
$k = array_rand($DexArray);
$v = $array[$k]['href'];
I get an error message saying: undefined variable: array in this line "$v = $array[$k]['href'];"
Do you have a solution for this?
It should be
$k = array_rand($DexArray);
$v = $DexArray[$k]['href'];
Here's a working debug :) link
There was a lingering , in your thingy. And $array was never defined in the first place, so that's what the error was telling you about.
Execute the code it will return the random value from the multidimensional php array.
<?php
$filter_field = array();
$original_items = array(
array(1, 'stuff1', 'info1', 'response1', 'info1', 'response1'), array(2, 'stuff2', 'info2', 'response2', 'info2', 'response2'), array(3, 'stuff3', 'info3', 'response3', 'info3', 'response3'), array(4, 'stuff4', 'info4', 'response4', 'info4', 'response4'));
for ($x = 0; $x < sizeof($original_items); $x++) {
array_push($filter_field, $original_items[$x][0]);
}
shuffle($filter_field);
echo "<br/><br/><br/>";
for ($x = 0; $x < sizeof($original_items); $x++) {
$k = $filter_field[$x];
for ($y = 0; $y < 5; $y++) {
echo $original_items[$k-1][$y];
}
echo "<br/><br/>";
}
?>
Here is another solution that will return the index of the random array.
$var = array(
array("a", "one"),
array("b", "two"),
array("c", "three"),
array("d", "four"),
array("e", "five"),
array("f", "six"),
array("g", "seven")
);
// array_rand returns the INDEX to the randomly
// chosen value, use that to access the array.
$finalVar = $var[array_rand($var)];
print_r($finalVar);
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.
I'm facing a complex task that make me headache. Assuming that I have option array like this:
$options = {'Color' => {'Red, Green, Blue'},
'Size' => {'S','M','L'},
'Material' => {'Wool','Cotton'}
}
Also, I have a set of mapping:
{'Red', 'S', 'Cotton'}
{'Red', 'M', 'Cotton'}
{'Blue', 'S', 'Wool'}
When I select an option by a certain way (from selectbox etc..), for example, when I select 'Red' I want to have an array like this:
$redArray = {
'Size' => {'S','M'},
'Material' => {'Cotton'}
}
Similarly, when I select 'M' option, the result will be:
$mArray = {
'Color => {'Red'},
'Material' => {'Cotton'}
}
Maybe my explanation is not clear enough, hope you can help me...Thanks
use array_merge_recursive for example
$ar1=array('color'=>"green");
$ar2=array('color'=>"blue");
$result = array_merge_recursive($ar1, $ar2);
output :
Array
(
[color] => Array
(
[0] => green
[1] => blue
)
)
input:
{Red, Medium, Cotton}
{Red, Large)
{Blue, Medium)
(Green, Small)
(Green, Large)
$r = array();
foreach($input as $i)
{
$k = $i[0];
foreach(array_slice($i, 1) as $s) {
$r[$k][] = $s;
$r[$k][] = array_unique($r[$k]);
}
}
With simple foreach is easy
// Your initial arrays
$from = array(
array("Red", "Medium"),
array("Red", "Large"),
array("Blue", "Medium"),
array("Green", "Small"),
array("Green", "Large")
);
// The output array
$output = array();
for ($i = 0; $i < count($from); $i++) {
$a = $from[$i];
if (!array_key_exists($a[0], $output) {
$output[$a[0]] = array();
}
if (!in_array($a[1], $output[$a[0]]) {
$output[$a[0]][] = $a[1];
}
}
Note that it could be easier to take simple key/value array in the from variable.
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').
?>