This is my array:
Array
(
[0] => Array
(
[id] => 1387
[form_id] => 2
[date_created] => 2018-05-17 21:34:37
----> [67] => a:1:{i:0;a:7:{s:17:"wp_attachement_id";i:5828;s:9:"mime_type";s:9:"video/mp4";s:9:"file_path";s:89:"/home/xxx/public_html/wp-content/uploads/2018/05/703c94b2b97a6479113d9e3020952891.mp4";s:5:"title";s:3:"xxx";s:11:"description";s:3:"xxx";s:8:"video_id";s:6:"QRSTUV";s:9:"video_url";s:43:"https://www.youtube.com/watch?v=QRSTUV";}}
[36] => New Harpshire
[34] => Borristown
)
)
The following will print the video id:
$undid = unserialize($entry['0']['67']);
echo $undid['0']['video_id'];
The problem is the number '67' does not remain constant. How do I retrieve that video_id if I have no idea what '67' will be?
I whipped up a quick Demo for you.
Ideally, you'd find a way to set the key to a semantic name instead of '67'
. But if you can't, and it's always different, then your best bet is to check for the expected value.
Since you're expecting a serialized array, we can check for serialized values by running them through the unserialize()
function. Note: This will trigger E_NOTICE level errors, so you'll probably want to suppress those with @unserialize()
(the @
suppresses errors). While it's generally a bad idea to suppress errors, these are errors we're expecting to trigger, so they should be safe to ignore.
So, as we pass things through unserialize()
, we can check if it sets $undid
to a truthy value. Once it does, we need to make sure we have the correct serialized information, so we can see if $undid[0]['video_id']
is set, and if it is, echo that value (or whatever else you want to do with it), and then break
the foreach
loop, since it no longer needs to run once our conditions have been met.
It's not exactly the most beautiful solution, but unless you can figure out how to name that key something semantic like file_upload_array
, your best bet is loop through the values until you find the one you need. As long as you don't have an unthinkable amount of fields, this should work fairly quickly.
$entry = [
[
'id' => 1387,
'form_id' => 2,
'date_created' => '2018-05-17 21:34:37',
'67' => 'a:1:{i:0;a:7:{s:17:"wp_attachement_id";i:5828;s:9:"mime_type";s:9:"video/mp4";s:9:"file_path";s:89:"/home/xxxxxxx/public_html/wp-content/uploads/2018/05/703c94b2b97a6479113d9e3020952891.mp4";s:5:"title";s:3:"xxx";s:11:"description";s:3:"xxx";s:8:"video_id";s:6:"QRSTUV";s:9:"video_url";s:43:"https://www.youtube.com/watch?v=QRSTUV22222";}}',
'36' => 'New Harpshire',
'34' => 'Borristown',
]
];
foreach( $entry[0] as $key => $val ){
if( $undid = @unserialize( $val ) ){ // unserialize returns E_NOTICE warnings on non-serialized items. @ suppresses that.
if( isset( $undid[0]['video_id'] ) ){ // Make sure this is the correct serialized field
echo $undid[0]['video_id'];
break;
}
}
}