PHP: извлечь первый экземпляр ISBN из JSON - PullRequest
0 голосов
/ 07 июня 2018

Привет, ребята, поэтому мне нужно извлечь первый экземпляр ISBN из JSON с помощью PHP.В приведенном ниже случае мне нужно 9781451687866. Я возвращаю записи книг из библиотечного API, и из-за характера вывода JSON книга может иметь 10 или 13-значные ISBN, связанные с ней. В любом случае мне нужен способ извлечения первого экземпляра13-значное число из строки в массиве и установка его равным переменной.если 13-значное число не существует, ищите 10-значное число типа ELSE «ISBN не найден».К вашему сведению: ISBN также могут начинаться с 0, так что мне нужно это сохранить.Есть идеи как этого добиться?Я использую цикл для вывода записей

for($i=0; $i<count($res['entries']); $i++) 
 ...echo "<h4>Title: " . $res['entries'][$i]['bib']['title'] . "</h4>";

НАМНОГО ценится!Спасибо

{
"count": 1,
"total": 1,
"start": 0,
"entries": [
  {
    "relevance": 72.32632446289062,
    "bib": {
      "id": "1386855",
      "varFields": [
        {
          "fieldTag": "a",
          "marcTag": "100",
          "ind1": "1",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "Buffett, Howard G."
            }
          ]
        },
        {
          "fieldTag": "c",
          "marcTag": "050",
          "ind1": "0",
          "ind2": "0",
          "subfields": [
            {
              "tag": "a",
              "content": "HV696.F6"
            },
            {
              "tag": "b",
              "content": "B84 2013"
            }
          ]
        },
        {
          "fieldTag": "d",
          "marcTag": "650",
          "ind1": " ",
          "ind2": "0",
          "subfields": [
            {
              "tag": "a",
              "content": "Food relief"
            },
            {
              "tag": "z",
              "content": "Developing countries."
            }
          ]
        },
        {
          "fieldTag": "d",
          "marcTag": "650",
          "ind1": " ",
          "ind2": "0",
          "subfields": [
            {
              "tag": "a",
              "content": "Agricultural development projects"
            },
            {
              "tag": "z",
              "content": "Developing countries."
            }
          ]
        },
        {
          "fieldTag": "d",
          "marcTag": "650",
          "ind1": " ",
          "ind2": "0",
          "subfields": [
            {
              "tag": "a",
              "content": "Humanitarianism"
            },
            {
              "tag": "z",
              "content": "Developing countries."
            }
          ]
        },
        {
          "fieldTag": "d",
          "marcTag": "650",
          "ind1": " ",
          "ind2": "0",
          "subfields": [
            {
              "tag": "a",
              "content": "Hunger"
            },
            {
              "tag": "z",
              "content": "Developing countries."
            }
          ]
        },
        {
          "fieldTag": "i",
          "marcTag": "020",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "9781451687866 (hardcover : alk. paper)"
            }
          ]
        },
        {
          "fieldTag": "i",
          "marcTag": "020",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "1451687869 (hardcover : alk. paper)"
            }
          ]
        },
        {
          "fieldTag": "i",
          "marcTag": "020",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "z",
              "content": "9781451687880 (ebook)"
            }
          ]
        },
        {
          "fieldTag": "i",
          "marcTag": "020",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "9781451687873 (pbk. : alk. paper)"
            }
          ]
        },
        {
          "fieldTag": "i",
          "marcTag": "020",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "1451687877 (pbk. : alk. paper)"
            }
          ]
        },
        {
          "fieldTag": "i",
          "marcTag": "020",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "1451687885 (ebook)"
            }
          ]
        },
        {
          "fieldTag": "i",
          "marcTag": "020",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "9781451687880 (ebook)"
            }
          ]
        },
        {
          "fieldTag": "l",
          "marcTag": "010",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "  2013031452"
            }
          ]
        },
        {
          "fieldTag": "n",
          "marcTag": "504",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "Includes bibliographical references (pages 417-423) and index."
            }
          ]
        },
        {
          "fieldTag": "n",
          "marcTag": "505",
          "ind1": "0",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "Acknowledgments -- Foreword -- Introduction: one shot at a warlord -- Story 1: How I realized i had only \"40 chances\" -- Story 2: Prague, 1968 : \"The army eats first : we get what is left\" -- Story 3: From bulldozing dirt to planting soil -- Story 4: Devon's gift -- Story 5: Because \"al called\" -- Story 6: The ovarian lottery -- Story 7: Reality has a nutty taste, especially when fried -- Story 8: Where hunger hides -- Bravery, courage, and hope -- Story 9: Loved, but lost -- Story 10: Empty calories -- Story 11: Little cromite -- Story 12: Sex and hunger in Timbuktu -- Story 13: Loss in Armenia -- Story 14: Farming under fire -- Story 15: Seeds of change -- Story 16: Shakira -- Story 17: a franciscan padre in the Sierra Madre -- Story 18: Gorillas v. guerillas -- Hard-learned lessons -- Story 19: Can this village be saved? -- Story 20: A complicated legacy -- Story 21: For yields to go up, we have to look down -- Story 21 1/2: owners make better farmers -- Story 22: What does doing better look like? / by Howard W. Buffett -- Story 23: Disconnects -- Story 25: A six-beer insight -- Story 26: Less than sparkling -- Challenges we need to figure out -- Story 27: Elephants and experts -- Story 28: Can smarter carrots save soil? -- Story 29: Chains that unlock potential / by Howard W. Buffett -- Story 30: A walk to the well -- Story 31: Souped up yields from stripped down tools -- Story 32: Does aid plant seeds of violence? / by Howard W. Buffett -- Reasons to hope -- Story 33: Opening what once was cerrado -- Story 34: Chocolate-covered opportunities -- Story 35: Fired up in Ghana -- Story 36: Buy local! -- Story 37: Hungry for data -- Story 38: The power of a piece of paper -- Story 39: Farmer of the future / by Howard W. Buffett -- Story 40: Help for a \"poor relation\" -- Epilogue: an optimistic pessimist returns to prague."
            }
          ]
        },
        {
          "fieldTag": "n",
          "marcTag": "520",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "If you had the resources to accomplish something great in the world, what would you do? Legendary investor Warren Buffett posed this challenge to his son in 2006, when he announced he was leaving the bulk of his fortune to philanthropy. Howard G. Buffett set out to help the most vulnerable people on earth--nearly a billion individuals who lack basic food security. And Howard has given himself a deadline: 40 years to put more than $3 billion to work on this challenge. Howard learned this lesson through his passion for farming: each farmer can expect to have about 40 growing seasons, giving him just 40 chances to improve on every harvest. This lesson applies to all of us, because we all have about 40 productive years to do the best job we can, whatever our passions may be. This book captures Howard's journey around the world as he seeks out new approaches to ease the suffering of so many.--From publisher description."
            }
          ]
        },
        {
          "fieldTag": "o",
          "marcTag": "001",
          "ind1": " ",
          "ind2": " ",
          "content": "830352188"
        },
        {
          "fieldTag": "p",
          "marcTag": "264",
          "ind1": " ",
          "ind2": "1",
          "subfields": [
            {
              "tag": "a",
              "content": "New York :"
            },
            {
              "tag": "b",
              "content": "Simon & Schuster,"
            },
            {
              "tag": "c",
              "content": "2013."
            }
          ]
        },
        {
          "fieldTag": "r",
          "marcTag": "300",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "xiv, 443 pages :"
            },
            {
              "tag": "b",
              "content": "illustrations ;"
            },
            {
              "tag": "c",
              "content": "24 cm"
            }
          ]
        },
        {
          "fieldTag": "r",
          "marcTag": "336",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "text"
            },
            {
              "tag": "2",
              "content": "rdacontent"
            }
          ]
        },
        {
          "fieldTag": "r",
          "marcTag": "337",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "unmediated"
            },
            {
              "tag": "2",
              "content": "rdamedia"
            }
          ]
        },
        {
          "fieldTag": "r",
          "marcTag": "338",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "volume"
            },
            {
              "tag": "2",
              "content": "rdacarrier"
            }
          ]
        },
        {
          "fieldTag": "t",
          "marcTag": "245",
          "ind1": "1",
          "ind2": "0",
          "subfields": [
            {
              "tag": "a",
              "content": "40 chances :"
            },
            {
              "tag": "b",
              "content": "finding hope in a hungry world /"
            },
            {
              "tag": "c",
              "content": "by Howard G. Buffett ; with Howard W. Buffett ; foreword by Warren E. Buffett."
            }
          ]
        },
        {
          "fieldTag": "u",
          "marcTag": "246",
          "ind1": "3",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "Forty chances"
            }
          ]
        },
        {
          "fieldTag": "y",
          "marcTag": "003",
          "ind1": " ",
          "ind2": " ",
          "content": "OCoLC"
        },
        {
          "fieldTag": "y",
          "marcTag": "005",
          "ind1": " ",
          "ind2": " ",
          "content": "20140117012148.0"
        },
        {
          "fieldTag": "y",
          "marcTag": "008",
          "ind1": " ",
          "ind2": " ",
          "content": "130905s2013    nyua     b    001 0 eng  cam i "
        },
        {
          "fieldTag": "y",
          "marcTag": "035",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "(OCoLC)830352188"
            }
          ]
        },
        {
          "fieldTag": "y",
          "marcTag": "040",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "DLC"
            },
            {
              "tag": "b",
              "content": "eng"
            },
            {
              "tag": "e",
              "content": "rda"
            },
            {
              "tag": "c",
              "content": "DLC"
            },
            {
              "tag": "d",
              "content": "YDXCP"
            },
            {
              "tag": "d",
              "content": "BDX"
            },
            {
              "tag": "d",
              "content": "OCLCO"
            },
            {
              "tag": "d",
              "content": "IH7"
            },
            {
              "tag": "d",
              "content": "YBM"
            },
            {
              "tag": "d",
              "content": "BUR"
            },
            {
              "tag": "d",
              "content": "GPI"
            },
            {
              "tag": "d",
              "content": "VP@"
            },
            {
              "tag": "d",
              "content": "WIQ"
            },
            {
              "tag": "d",
              "content": "EEK"
            },
            {
              "tag": "d",
              "content": "OCLCF"
            },
            {
              "tag": "d",
              "content": "IXA"
            },
            {
              "tag": "d",
              "content": "BET"
            }
          ]
        },
        {
          "fieldTag": "y",
          "marcTag": "042",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "pcc"
            }
          ]
        },
        {
          "fieldTag": "y",
          "marcTag": "043",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "d------"
            }
          ]
        },
        {
          "fieldTag": "y",
          "marcTag": "049",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "BETT"
            }
          ]
        },
        {
          "fieldTag": "y",
          "marcTag": "994",
          "ind1": " ",
          "ind2": " ",
          "subfields": [
            {
              "tag": "a",
              "content": "C0"
            },
            {
              "tag": "b",
              "content": "BET"
            }
          ]
        },
        {
          "fieldTag": "_",
          "content": "00000cam  2200000 i 4500"
        }
      ]
    }
  }
]

}

Ответы [ 2 ]

0 голосов
/ 09 июня 2018

Похоже, это решает мою проблему.Спасибо всем

for($q=0; $q<count($res['entries'][$i]['bib']['varFields']); $q++) //loop thru the varFields
{


    if($res['entries'][$i]['bib']['varFields'][$q]['fieldTag'] == "i") //pull out only ISBN fieldTags with a value i
        {


            $subfieldText = $res['entries'][$i]['bib']['varFields'][$q]['subfields'][0]['content'];
            if (preg_match_all("/\d{13}/", $subfieldText, $matches))
                {
                $isbnDetect = $matches[0];
                echo $isbnDetect[0];
                break;   //if we match a 13 digit ISBN leave conditional
                }
             else if (preg_match_all("/\d{10}/", $subfieldText, $matches))
                 {
                 $isbnDetect = $matches[0]; 
                 echo $isbnDetect[0];
                 break;  //else if we match a 10 digit ISBN leave conditional
                 }

          } 

    else
    {
        $isbnDetect[0] = ""; //if no ISBN clear value
    }



}
0 голосов
/ 08 июня 2018

Я определенно не эксперт по ISBN. Так что это может не сработать в каждом сценарии.Это может быть для вас отправной точкой, потенциально.

$str1 = 'isbn: 1234567890';
$str2 = 'isbn: 123-1234567890';
$str3 = 'isbn: 1234567890123';

//matches 3 digits, then a hyphen, then 10 digits OR
//matches 10 digits in a row
$regex = '/\d{3}-\d{10}|\d{10}/';

preg_match($regex, $str1, $result1);
preg_match($regex, $str2, $result2);
preg_match($regex, $str3, $result3);

var_dump($result1);
var_dump($result2);
var_dump($result3);

Независимо от того, на какую строку она подается, она будет извлекать 10 цифр подряд или 13 цифр, если между ними стоит -.

...