How to search in this multidimensional array by using PHP?

Hi Experts

Could you point how to use an array_search in a multidimensional array like is presented now in a manner it could be filtered using parameters like

 [slug]
 [title]
 [overview]

The array was serialized and saved in this .txt

Since I'm building a MOC I couldn't persist in DB by now.

Thanks in advance!
array.txt
Eduardo FuerteAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
from documentation and this comment  : http://php.net/manual/fr/function.array-search.php#116635

$key = array_search('sons-of-anarchy-2008', array_column($arr, 'slug'));
$key = array_search('Sons of Anarchy', array_column($arr, 'title'));

$record = $arr[$key];
0
Eduardo FuerteAuthor Commented:
I guess something else is necessary...

img005
Generates this error:
img006
Could you check?
0
Eduardo FuerteAuthor Commented:
I guess this make it easy to undestand the array structure:
array_structure.txt
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

leakim971PluritechnicianCommented:
currently you've only one object in you array, you can simply do :

$slug = $arr->slug;
$title = $arr->title;

Open in new window

0
Eduardo FuerteAuthor Commented:
I obtained a discrete value similarly since I'm using array

My doubt is
<?php

   $jsonstring = '....';  // very long

   $arr = json_decode($jsonstring, true);

   $slug = $arr['slug'];
   $title = $arr['title'];

//OK   it's printed
//   print_r($slug);
//   print_r($title);
   

// Search a film
$cont=0;    
foreach ($arr as $key ) {
       if ($arr['title'] === 'Suits of Woe') {

           // How to obtain all the other features of the film.... 


          //
           break;
       }
       else
         $cont++;
   }
  
      print_r($cont);

?>

Open in new window

0
leakim971PluritechnicianCommented:
0
Eduardo FuerteAuthor Commented:
@leakim971

I guess I didn't expressed me well..

My doubt here is related on how to "transverse" the intire array, seaching for the desired elements, my starting point is the foreach -  a merely suggested code I'm not confident on it.

(or maybe,  instead of it to collect the data and insert in a MySQL table)
0
leakim971PluritechnicianCommented:
if you us array_keys, you get all keys in an array so you will be able to use foreach on this array

$arr = json_decode($jsonstring, true);
$keys = array_keys($arr); // ["slug","title",...
foreach($keys as $key)
{
    echo $key . "<BR />"; // will display all field in the page : slug, title, ...
}

Open in new window

0
Eduardo FuerteAuthor Commented:
Ok.
Going this way I get the key names...

But then I need to obtain the contents.

What I tryed with no success is:
   for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i]['id'];
    echo $arr[$i]['title'];
	//...etc
}

Open in new window

Could you check?
0
Eduardo FuerteAuthor Commented:
Just to complement

Running this code:
foreach($arr as $item) {
    echo '<pre>'; 
    var_dump($item);
}

Open in new window


string(36) "a8e8fefb-a0c9-4d2a-b088-71160da74c1c"

string(20) "sons-of-anarchy-2008"

string(15) "Sons of Anarchy"

string(513) "An adrenalized drama with darkly comedic undertones that explores a notorious outlaw motorcycle club’s (MC) desire to protect its livelihood while ensuring that their simple, sheltered town of Charming, California remains exactly that, charming. The MC must confront threats from drug dealers, corporate developers, and overzealous law officers. Behind the MC’s familial lifestyle and legally thriving automotive shop is a ruthless and illegal arms business driven by the seduction of money, power, and blood."


Just this keys:

['id']
['slug']
['title']
['overview']
0
Julian HansenCommented:
I don't understand the question.

The data you posted only has one element with slug and title.

Are there meant to be other items with these fields?
0
Eduardo FuerteAuthor Commented:
Hi

Accordingly to @leakim971's code      
    $jsonstring = '....' // very long
   
    $arr = json_decode($jsonstring, true);
    
	$keys = array_keys($arr); // ["slug","title",...
	foreach($keys as $key)
	{
		echo $key . "<BR />"; // will display all field in the page : slug, title, ...
	} 

Open in new window


The keys are:
img001
The original array is  at the question and at ID: 42426038
0
Julian HansenCommented:
Yes I understand - I have the array and have deserialised it - however you appear to be asking how to filter the array based on the slug field and the root array has only one entry with a field called slug. So I am confused as to how you want to filter the array.
0
Eduardo FuerteAuthor Commented:
Ok.

Filter the array by a key is my initial objective.

During the question evoltion I conclude that  better than it is

How to transverse the array by using it's keys - obtaining every key values and persisting it inserting in a MySQL table (f.e.).

I hadn't found a way to obtain the key values during the array transversion,
0
Eduardo FuerteAuthor Commented:
By "key values" I meant:

Accordingly to my attempt in
ID: 42427128

echo $arr[$i]['title']; // 'Sons of Anarchy';

Open in new window

0
leakim971PluritechnicianCommented:
let"s say arrays are boxes
somes boxes contains boxes and sometimes items too and not only items

for example, "seasons" are a box with boxes inside ( [availability] and [episodes]) and items ([id], [number])
you can test if the item of an array is a box so transverse this new array too but I'm not sure it's the right way to work.
you should know what you need to store and find the path (the boxes to open) to get the item you are looking for to save it in the database
0
Eduardo FuerteAuthor Commented:
So... transverse this particular array to get specifically values looks to be a "grand expedition"...
0
leakim971PluritechnicianCommented:
not if you know what you are looking for, use this tools for example to travel : http://jsonviewer.stack.hu/
paste the JSON object in the "text" tab and use the "viewer" tab to travel
jsonviewer
0
Eduardo FuerteAuthor Commented:
This case we return back to .json (not else an array).
Then parsing it by using jQuery f.e. ?
0
Julian HansenCommented:
I hadn't found a way to obtain the key values during the array transversion,
To iterate over an array and access both keys and values you do this
echo "<pre>";
foreach($data as $key => $value) {
  echo "----------------------------------------------------------------------------------------------------------------\n";
  echo "Key : [{$key}] => ";
  print_r($value); 
  echo "\n";
}
echo "</pre>";

Open in new window

Working sample here
I am guessing this is what you want - I am struggling to understand otherwise what you are wanting to achieve.
0
Julian HansenCommented:
This case we return back to .json (not else an array).
I think leakim was trying to show you how to visualise the array so we could talk about it.

Eduardo - can you explain exactly what it is you want to do with this data. I think we are going around in circles here because of a communication problem - if you can give us a clear idea of what you want to do with the data we can take it from there.

From what I can tell you have given us an array of key value pairs
Some of the values are scalar other values are arrays.

In your OP you said you want to filter the array by
 [slug]
 [title]
 [overview]
However in the data you gave us these keys appear only once - which means that "filter" is not the right word.

I know from interacting with you on previous questions that you have a sound knowledge of PHP so we are not talking about basic array access.

So, I am confused as to what it is you are actually wanting to know.

Describe what it is you want to get out of the data - that will help us to understand better.
0
Eduardo FuerteAuthor Commented:
Julian

Your last code is very closer to what I need, with my own adaptions:

foreach($arr as $key => $value) {
   $astr = is_array($value) ? '(array)' : '';

	if($key=='id')
	{
		$id = $value;
		print_r($value); 
		echo "<BR />";
	}
   
	if($key=='title')
	{
		$title = $value;
		print_r($value); 
		echo "<BR />";
	}
	
	if($key=='imdb_rating')
	{
		$imdb_rating = $value;
		print_r($value); 
		echo "<BR />";
		 
		// Mysql insertion here... f.e. just capturing these 03 values
		
	}
}

Open in new window


Just one thing, the loop breaks after the 1st interaction (?!)

img002
0
leakim971PluritechnicianCommented:
This case we return back to .json (not else an array).
Then parsing it by using jQuery f.e. ?
No the JSON representation help you find what you're looking for

Just one thing, the loop breaks after the 1st interaction (?!)
Normal, you have only one big box with all the items and some other boxes inside
You want to loop over what ? episodes seasons ?
0
Eduardo FuerteAuthor Commented:
1st of all Julian and Leakim, thank you for your patience in help me!

Normal, you have only one big box with all the items and some other boxes inside
You want to loop over what ? episodes seasons ?

Maybe I misconcept things.  The foreach to transverse the films and its atributes one of a time....
0
Julian HansenCommented:
Which films?

The data you gave us is an array of 1.
0
leakim971PluritechnicianCommented:
currently, you've only one movie (televesion serie) in the file
let's say you've all the keys, how are you going to store that in the database ? you need to create multiple table, not one, the top attributes ( comment 42427277
3h) are columns (example : id,title,slug)  or foreign keys (episodes, sources,seasons). for each foregin key, you should create another table and store the content of the box which may have some new foreign keys.

instead, create FIRST your database model and select what you want to save. you may use the JSON structure to  help you

else the other option is to go to a non relational database like mongodb and which let you easily save the whole object in one shot as suggested in your previous question
0
Eduardo FuerteAuthor Commented:
You are right.

What I meant is to break in episodes - not films.
0
Eduardo FuerteAuthor Commented:

currently, you've only one movie (televesion serie) in the file
let's say you've all the keys, how are you going to store that in the database ? you need to create multiple table, ...

First, for simplicity I need to persist just in 02 tables - Films/ Episodes(f.e.) just to gain know how - after this done, I will modelize the other tables, foreign keys...
0
leakim971PluritechnicianCommented:
see if that help, also, check comments inline :

$arr = json_decode($jsonstring);
$keys = array_keys($arr); // ["slug","title",...

echo "<h1>main attributes : </h1>". "<BR>";
foreach($keys as $key)
{
    if(!is_array($key)) // we want to display only top box (id, slug, title)
    {
        echo $key . "<BR />";
    }
}

echo "<BR><BR>";

// now the box of episodes
echo "<h1>episodes : </h1>". "<BR>";
foreach($arr["episodes"] as $episode)
{
//    var_dump($episode);
//    echo "<BR />";

    echo "<h4>title of the episode :" . $episode["title"] . "</h4>";

    // maybe you want to get all attributes of an episde :
    $episode_keys = array_keys($episode);
    foreach ($episode_keys as $episode_attribute) {
        //echo $episode_attribute; // display every attribute for every episode
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Eduardo FuerteAuthor Commented:
leakim971

Your last code is very near to what I need....
Just one thing more  - I'm still trying by myself

Obtain the film attributes (main table).
img004
0
Eduardo FuerteAuthor Commented:
trailler isn't necessary.
0
Eduardo FuerteAuthor Commented:
Sorry, extremelly easy....
	print_r($arr['id']);
	
	print_r($arr['title']);

Open in new window

0
leakim971PluritechnicianCommented:
$arr = json_decode($jsonstring);

$title = $arr["title"];
$slug = $arr["slug"];
0
Eduardo FuerteAuthor Commented:
I admit my question was very confused... vague and difficult to follow.

Thank you for the attention you give me to solve it!
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.