Link to home
Start Free TrialLog in
Avatar of Eduardo Fuerte
Eduardo FuerteFlag for Brazil

asked on

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
Avatar of leakim971
leakim971
Flag of Guadeloupe image

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];
Avatar of Eduardo Fuerte

ASKER

I guess something else is necessary...

User generated image
Generates this error:
User generated image
Could you check?
I guess this make it easy to undestand the array structure:
array_structure.txt
currently you've only one object in you array, you can simply do :

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

Open in new window

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

@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)
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

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?
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']
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?
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:
User generated image
The original array is  at the question and at ID: 42426038
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.
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,
By "key values" I meant:

Accordingly to my attempt in
ID: 42427128

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

Open in new window

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
So... transverse this particular array to get specifically values looks to be a "grand expedition"...
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
User generated image
This case we return back to .json (not else an array).
Then parsing it by using jQuery f.e. ?
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
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 (?!)

User generated image
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 ?
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....
Which films?

The data you gave us is an array of 1.
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
You are right.

What I meant is to break in episodes - not films.

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...
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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).
User generated image
trailler isn't necessary.
Sorry, extremelly easy....
	print_r($arr['id']);
	
	print_r($arr['title']);

Open in new window

$arr = json_decode($jsonstring);

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

Thank you for the attention you give me to solve it!