How to get an array from a saved custom field - php

I save my array of integers in a custom fields with the function:
update_post_meta($post->ID, "images", array(1, 2, 50));
How can I load this array now?
I try to use something like this, but without any luck:
global $post;
$custom = get_post_custom($post->ID);
$myarray = $custom["images"][0];
echo $custom["images"];
It returns something like a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:2:"50";}
May be I can parse this string to get an array from this?

May be I can parse this string to get an array from this?
This is a serialized array.
Use unserialize() to unpack it.

Related

Convert multiple array into a string in laravel

$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->get(array('id'));
return $est_data;
result:
[{"id":43},{"id":71},{"id":41},{"id":39}]
This is my above laravel condition and result, i want the result to be like 43,71,41,39.
Can anyone please help me, how can be this done using php. i tried with implode() function, but getting error, please help...thank you
Laravel pluck method will select required fields only:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return $est_data;
As commented by #apokryfos for your laravel version (4.2) lists method should be used, so it is:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->lists('id');
return $est_data;
You can use the laravel array_flatten() array helper:
The array_flatten function flattens a multi-dimensional array into a
single level array:
$array = array('name' => 'Joe', 'languages' => array('PHP', 'Ruby'));
$array = array_flatten($array);
// array('Joe', 'PHP', 'Ruby');
In your case:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return array_flatten($est_data);
$result = implode(',',$est_data[0]);
This will solve your problem. You should read about implode(convert to string) and explode (string to array). They are really useful php functions.
Reading your comment, your error is coming from the fact that you try to access $set_data and not $set_data[0] where you values are based on the output you provided us.
Use the php array_column function, specifying the id:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return array_column("id", $est_data);

merging and then sorting 2 arrays in php & wordpress

I'm trying to merge 2 arrays in PHP and then sort them.
I'm pulling data from WordPress database ( tags and categories ) and I need to merge them and sort them properly.
Code looks similar to this:
$categories = [
'<a>WordPress Tips</a>',
'<a>SEO Tips'</a>,
'<a>Development Tips</a>'
];
$tags = [
'<a>WordPress</a>',
'<a>SEO'</a>,
'<a>Development</a>'
];
$taxonomies = array_merge($categories, $tags);
sort($taxonomies);
Since I need to loop through $taxonomies array and print them with anchors included ( every one of those must have a valid URL to itself ), I don't get a proper sorting result. However, as soon as I 'strip out' all the tags around these items, sorting works as it should, but I don't get URLs that I need, only string / text.
Could someone suggest a better sorting algorithm which would sort these items properly with html elements included around them? Thanks!
You need to do custom comaprision to make it work using usort() and strip_tags()
<?php
$taxonomies = array_merge($categories, $tags);
print_r($taxonomies);
function cmp($a, $b){
$data1 = strip_tags($a);
$data2 = strip_tags($b);
return ($data1 < $data2) ? -1 : 1;
}
usort($taxonomies, "cmp");
print_r($taxonomies);
Output:-https://eval.in/934071
Since you mentioned that the tags stripped version works, a simple way might be to use them as the keys in the sort. Something like this, for instance :
$taxonomies = array_merge( $categories, $tags );
$toSort = [];
foreach($taxonomies as $tax) {
$toSort[strip_tags($tax)] = $tax;
}
ksort( $toSort );
print_r( $toSort );
Which will give the sorted array and you can just use the values in there. Maybe there's better options but this comes to mind off the top of my head..
EDIT : uasort with a comparision function that actually compares the stripped versions might be better, after looking at other answers here.

Wordpress output to array in query from custom field

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
);

Laravel Store Array in Session

I have been having trouble storing an array in session. I am making a shopping cart and it doesn't seem to work.
public function __construct(){
$product = array(1,2,3,4);
Session::push('cart', $product);
}
and then retrieve it in the view like this.
{{Session::get('cart')}}
However I keep getting an error like this.
htmlentities() expects parameter 1 to be string, array given
Any clues and advice on how to create a shopping cart that stores an array of items.
If you need to use the array from session as a string, you need to use Collection like this:
$product = collect([1,2,3,4]);
Session::push('cart', $product);
This will make it work when you will be using {{Session::get('cart');}} in your htmls. Be aware of Session::push because it will append always the new products in sessions. You should be using Session::put to be sure the products will be always updating.
You're storing an array in the session, and since {{ }} expects a string, you can't use {{Session::get('cart')}} to display the value.
The {{ $var }} is the same as writing echo htmlentities($var) (a very simple example).
Instead, you could do something like:
#foreach (Session::get('cart') as $product_id)
{{$product_id}}
#endforeach
If you use 'push', when initially creating the array in the session, then the array will look like this:
[
0 => [1,2,3,4]
]
Instead you should use 'put':
$products = [1,2,3,4];
$request->session()->put('cart', $products);
Any subsequent values should be pushed onto the session array:
$request->session()->push('cart', 5);
You can use .:
$product = array(1,2,3,4);
Session::put('cart.product',$product);
You can declare an array in session like
$cart = session('data', []);
$cart[] = $product;
session([ 'data' => $cart]);
return session('data', []);
you can also do it like that:
$data = collect($Array);
Session()->put('data', $data);
return view('pagename');

Really simply wordpress array issue

I cannot figure this out, when I use get_post_meta, like so
$meta = get_post_meta( get_the_ID() );
Its returns an array but printing a key such as weight like this
echo $meta['weight'];
returns another array, how am I able to use this as I simply want to print the value rather than this if I use print_r
Array ( [0] => 12313 )
I really would like to get all the values in this was as I have over 60 custom fields and do not want to have 60 lines to get each custom field individually :(
Many thanks
Try this:
echo $meta['weight'][0];

Categories