PHP - 搜索数组并存储值

时间:2017-12-01 05:33:07

标签: php arrays strpos

我遇到了麻烦。我从Youtube中提取播放列表项目的数据并使用歌曲标题将播放列表组织成特定的艺术家阵列。

这就是数组的样子

$playlistMaster = array (
    'foo fighters' => array(),
    'queens of the stone age' => array(),
    ...
    ...
    'misc' => array()
)

这是我正在处理的用于存储到数组的代码

//For each playlist item
    foreach($playlist->items AS $item):
        // Stores the song title in a var and makes it lowercase
        $str = $item->snippet->title;
        $str = strtolower($str);

        // Stores the last key of the array
        $last = end($playlistMaster);

        // Takes the first key of the array and checks to see if the song title matches the key name
        $keyString = key($playlistMaster);
        $pos = strpos($str, $keyString);

        // If it is not a match, then move on to the next key, if it reaches the end of the arrays then store that song in the last array.
        if ($pos === false) {
            next($playlistMaster);

            if (next($playlistMaster) === $last) {
                $songId = $item->snippet->title;
                array_push($playlistMaster[$keyString], $songId);
                reset($playlistMaster);
            }                   

            $keyString = key($playlistMaster);
            $pos = strpos($str, $keyString);
        }

        // Else if it is a match then store that song in the current array.
        else {
            $songId = $item->snippet->title;
            array_push($playlistMaster[$keyString], $songId);
            reset($playlistMaster);
        }
    endforeach; 

希望,这有什么意义吗?我目前没有错误,但没有任何存储到任何阵列,也没有找到一种方法来“逐步”PHP,就像我用Java一样,找出每一步发生了什么,所以我得到一个有点沮丧,没有反馈继续下去。

感谢。

1 个答案:

答案 0 :(得分:0)

检查以下代码,这可能会达到您的要求。

<?php

$playlistMaster = array (
    'foo fighters' => array('aaa'),
    'queens of the stone age' => array('bbb'),
    'misc' => array('ccc')
);

$playlist = array('ar' => 'ddd','misc' => 'eee');
//For each playlist item
//key is author and value is title/song
    foreach($playlist AS $key=>$val) {
        if(isset($playlistMaster[$key])) {
            if(!in_array($val,$playlistMaster[$key])) {
                array_push($playlistMaster[$key],$val);
            }
        } else {
            $playlistMaster[$key] = array($val);
        }
    }
echo '<pre>';
print_r($playlistMaster);
print_r($playlist);