In my foreach loop, I am creating an array for each post I loop through. This array contains various post elements that I want to add to a new array and post back via ajax. I want to create a single array with multiple arrays inside that I can then encode and send. Each array looks like this and I'm looping through about 20 times.
$postdata = array(
'thumb'=>$thumb,
'title'=>$title,
);
What Im looking for is this:
array(
array(
'thumb'=>$thumb,
'title'=>$title,
)
array(
'thumb'=>$thumb,
'title'=>$title,
)
etc...
)
I tried array_merge but this didn't work. I'm guessing its something along the lines of:
$postsarray = array();
foreach($posts as $p){
$array = array('thumb'=>$thumb,'title'=>$title);
$postsarray[] = $array;
}
But that still didn't work. I got an empty array with no arrays inside.
Related
I have an XML which includes many thousands of nodes with information about them in attributes.
Each node is like :
<Class Option1="fiahfs;if" Option2="fiowfr0r0" ClassID="1">
<Class Option1="ro;ewaj;frwajro" Option2="afj;wh;fha" Option3="34014upkla" ClassID="2">
....
I need to parse that info into PHP arrays with array names being attribute names and the number of element in array equal to ClassID Attribute.
The problem is that some nodes have attributes that other nodes I dont have. I previously used ->attributes() for one selected element as
$a => $b,
$$a=array();
then
${$a}[(integer)$products['ClassID']]=$b
Where $products is simplexml element got from parsing XML with xpath. That basically gave me what i needed - i had a few arrays and i could address my requests like $Option1[1] , $Option2[1], Option1[2]...etc.
But the problem is that if I create that structure using only attribute list of one selected element -there`ll be elements that that one element do not have,but other have, and after a create arrays and then parse XML -there'll not be some arrays. Like if i create arrays from [0] of that example, that will give me $Option1, $Option2, but no $Option3.
When I rebuilt my code to :
foreach ($XML->xpath('/idspace/Class') as $products){
foreach($products->attributes() as $a => $b){
if(!isset($$a) $$a=array();
${$a}[(integer)$products['ClassID']]=$b;
}}
And after that I tried to foreach($ClassID) - I`ve got only one element in that array.
How can I parse every XML attribute to array while using attribute "ClassID" as element number in array?
I'm quite confused with your arrays. For me it sounds strange to have an extra array for each attribute. Why not make one array that contains each element and have the attributes as children. So that in the end you get an array like this:
$products = array(
[1] => array(
[Option1] => "fiahfs;if",
[Option2] => "fiowfr0r0",
),
[2] => array(
[Option1] => "ro;ewaj;frwajro",
[Option2] => "afj;wh;fha",
[Option3] => "34014upkla",
),
In this way you can easily access all the attributes for a given ChildId:
$products[$childId]['Option1'] - or better check if the Attribute-Name exists.
You can use simplexml->attributes()
$products = array(); // products will have the result!
foreach ($xml->products as $productXml) { // don't know your xml structure here,
// but you need to iterate over every product in the xml
$singleProduct = array();
$classId = 0;
foreach($productXml->attributes() as $a => $b) {
if ($a == 'ClassID') {
$classId = $b;
} else {
$singleProduct[$a] = $b;
}
}
$products[$classId] = $singleProduct;
}
I have created a custom field named "sec1array" in my categories so that i can add an array, for example 1,2,3,4
I want to retrieve that array and output it in the loop, so I created this code.
$seconearray = array($cat_data['sec1array']);
$args = array(
'post__in' => $seconearray
);
However, it only seems to be outputting the first post in the array. Is it something to do with the way the comma is outputting?
If I print $seconearray it outputs correctly, example 1,2,3,4
What you are doing is storing a string value of "1,2,3,4" in your database which when you are trying to construct an array from it like array("1,2,3,4") you end up just assigning a single value to that new array. This is why it only contains a single value.
You need to store your value in a serializable format so it can be converted back to an array after you save it to the database. There are many ways to do this, I'm sure others will give more examples:
JSON encode it
json_encode(array(1,2,3,4)); // store this in your db
json_decode($cat_data['sec1array']); // outputs an array
Or, you can use PHP serialize
serialize(array(1,2,3,4)); // store this in your db
unserialize($cat_data['sec1array']); // outputs an array
If you want to keep your string, you can explode it:
explode(',', $cat_data['sec1array']); // outputs your array of 1,2,3,4.
Using any of these methods will work. Finally you'll end up with an example like:
$seconearray = explode(',', $cat_data['sec1array']);
$args = array(
'post__in' => $seconearray
);
Say I have an array like this
$posts = array(
array('post_title'=>10, 'post_id'=>1),
array('post_title'=>11, 'post_id'=>2),
array('post_title'=>12, 'post_id'=>3),
array('post_title'=>13, 'post_id'=>4),
array('post_title'=>10, 'post_id'=>5)
);
How can I remove the first dimensional element if one of its 'post_title' or 'post_id' value is repeated?
Example:
Suppose we know that 'post_title' is '10' in two first dimensional elements.
How can I remove the repeated element from $posts?
Thanks.
Create a new array where you will store these post_title values. loop through $posts array and unset any duplicates. Example:
$posts = array(
array('post_title'=>10, 'post_id'=>1),
array('post_title'=>11, 'post_id'=>2),
array('post_title'=>12, 'post_id'=>3),
array('post_title'=>13, 'post_id'=>4),
array('post_title'=>10, 'post_id'=>5)
);
$tmp_array = array();
foreach ($posts as $i => $post)
{
if (!in_array($post['post_title'], $tmp_array)) // if it doesn't exist, store it
{
$tmp_array[] = $post['post_title'];
} else { // element exists, delete it
unset($posts[$i]);
}
}
Now in your $posts array you will have unique post_title values.
I have an array with 45 object elements containing id, name, is_premium.
From MySQL I receive them, ordered by is_premium desc, and some of them have is_premium = 0 at the end of list.
How can I randomize elements with is_premium=1, keeping the is_premium=0 at the end of array?
Try if this works:
<?php
//assuming the array of objects is called $array
$new_array = array_merge(
shuffle(
array_filter($array,function($x){return $x['is_premium'] == 1;})
),
array_filter($array,function($x){return $x['is_premium'] == 0;})
);
?>
So I have my query, its returning results as expect all is swell, except today my designer through in a wrench. Which seems to be throwing me off my game a bit, maybe its cause Im to tired who knows, anyway..
I am to create a 3 tier array
primary category, sub category (which can have multiples per primary), and the item list per sub category which could be 1 to 100 items.
I've tried foreach, while, for loops. All typically starting with $final = array(); then the loop below that.
trying to build arrays like:
$final[$row['primary]][$row['sub']][] = $row['item]
$final[$row['primary]][$row['sub']] = $row['item]
I've tried defining them each as there own array to use array_push() on. And various other tactics and I am failing horribly. I need a fresh minded person to help me out here. From what type of loop would best suit my need to how I can construct my array(s) to build out according to plan.
The Desired outcome would be
array(
primary = array
(
sub = array
(
itemA,
itemB,
itemC
),
sub = array
(
itemA,
itemB,
itemC
),
),
primary = array
(
sub = array
(
itemA,
itemB,
itemC
),
sub = array
(
itemA,
itemB,
itemC
),
),
)
Something like this during treatment of your request :
if (!array_key_exists($row['primary'], $final)) {
$final[$row['primary']] = array();
}
if (!array_key_exists($row['sub'], $final[$row['primary']])) {
$final[$row['primary']][$row['sub']] = array();
}
$final[$row['primary']][$row['sub']][] = $row['item'];
Something like this....
$final =
array(
'Primary1'=>array(
'Sub1'=>array("Item1", "Item2"),
'Sub2'=>array("Item3", "Item4")
),
'Primary2'=>array(
'Sub3'=>array("Item5", "Item6"),
'Sub4'=>array("Item7", "Item8")
),
);
You can do it using array_push but it's not that easy since you really want an associative array and array_push doesn't work well with keys. You could certainly use it to add items to your sub-elements
array_push($final['Primary1']['Sub1'], "Some New Item");
If I understand you correctly, you want to fetch a couple of db relations into an PHP Array.
This is some example code how you can resolve that:
<?php
$output = array();
$i = 0;
// DB Query
while($categories) { // $categories is an db result
$output[$i] = $categories;
$ii = 0;
// DB Query
while($subcategories) { // $subcategories is an db result
$output[$i]['subcategories'][$ii] = $subcategories;
$iii = 0;
// DB Query
while($items) { // $items is an db result
$output[$i]['subcategories'][$ii]['items'][$iii] = $items;
$iii++;
}
$ii++;
}
$i++;
}
print_r($output);
?>