Pass an array to objects in php

1
foreach ($video_filer['items'] as $video) {
    if (isset($video['id'])) {
        $date = new DateTime($video['snippet']['publishedAt']);
        $time = covtime($video['contentDetails']['duration']);
        //convert the date
        $video_date = date_format($date, 'd/m/y');
        //create the video list details
        $data[] = array(
            "thumbnail"   => $video['snippet']['thumbnails']['medium']['url'],
            "title"       => htmlspecialchars($video['snippet']['title'], ENT_QUOTES, 'UTF-8'),
            "title_short" => short_text_out(htmlspecialchars($video['snippet']['title'], ENT_QUOTES, 'UTF-8'), 4),
            "username"    => $video['snippet']['channelTitle'],
            "profile"     => "https://www.youtube.com/channel/" . $video['snippet']['channelId'],
            "views"       => (isset($video['statistics']['viewCount'])) ? $video['statistics']['viewCount'] : '',
            "date"        => $video_date,
            "time"        => $time,
            "more"        => 'https://www.youtube.com/watch?v=' . $video['id'],
            "embed_url"   => 'http://www.youtube.com/embed/' . $video['id'] . '?autoplay=1',
        );
    }
}
    
asked by Bryan Zavala 12.04.2018 в 06:09
source

2 answers

1

You can use json_encode and json_decode something like this:

<?php
/* silly random data generator */
function randData($maxChars=50, $intVals=false){
  $i = rand(0,$maxChars);
  $t = substr(str_repeat(md5(microtime()),$maxChars%26),rand(0,26),$maxChars);
  return $intVals?$i:$t;
}

$fileArray= array(
    "Category"=>randData(16),
    "Key"=>randData(32),
    "Value"=>randData(1000,true),
    "Description"=>randData(120)
  );

/* Array como Object  */
$fileObjeto = json_decode(json_encode($fileArray, JSON_FORCE_OBJECT));

echo "<pre>".PHP_EOL;
var_dump($fileArray);
var_dump($fileObjeto);
echo "</pre>".PHP_EOL;
    
answered by 12.04.2018 / 06:39
source
1

Another way to achieve this is to force the conversion to type object the syntax would be the following:

$Objeto = (object)$Array;

Here more information about type manipulation in PHP

I leave an example of use:

<?php


    $Array = array(
        "key1" => 'value1',
        "key2" => 'value2',
        "key3" => 'value3',
        "key4" => 'value4',
    );

    $Objeto = (object)$Array;

    echo "<pre>" . PHP_EOL;
    print_r($Array);
    print_r($Objeto);
    echo "</pre>" . PHP_EOL;
    
answered by 12.04.2018 в 08:39