How to replace array value

Asked

Viewed 385 times

0

That’s my code these days, I’d like to add the season (which I can already do) and then the episodes within this season (which I’m not getting to do).

<?php

$string = '[{"OVAS":[{"name":"01","file":"file01.mkv"},{"name":"02","file":"file02.mkv"}]},{"TEMP":[{"name":"01","file":"file01.mkv"},{"name":"02","file":"file02.mkv"}]}]';

$string = addSeason($string, 'Teste');
$string = addEpisodes($string, 'Teste', array('01', '02'), array('file01.mkv', 'file02.mkv'));

echo $string;

function addSeason($json, $name)
{
    $obj = json_decode($json, true);

    $obj[count($obj)][$name] = '';

    return json_encode($obj);
}
function addEpisodes($json, $season, $names, $files)
{
    $obj = json_decode($json, true);

    for($i=0; $i < count($names); $i++) 
    { 
        $data[$i]['name'] = $names[$i];
        $data[$i]['file'] = $files[$i];
    }

    foreach ($obj as $k => $seasons) 
    {
        foreach ($seasons as $s => $episodes) 
        {
            if($s == $season)
            {
                $episodes = $data;
            }
        }
    }

    return json_encode($obj);
}
  • Try to put foreach ($seasons as $s => &$episodes) (with the &) at last foreach, to define $episodes as a reference and allow you to change the value by the assignment you are making.

  • I tried with the & at the front and it didn’t work, you know some other way ??

  • Also add to foreach of $seasons, but need necessarily do so? Why convert to string all the time?

  • I even saw some ways to put in json, but I didn’t understand very well, if you want to improve the way I’m doing somehow, put as answer please :D

  • You cannot keep the list in array form even, no?

  • That’s why I’m going to save this to a database column.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.