Sorting very long json object with php - php

I am working with an API and i am trying to sort the json object it returns to me. Here is a small cut out of the json object
Now i want to sort this because i only want to save part of the data. Say i wanted to save the "_ID" here. THe data i need is really way further down but i think if i can figure out how to get this, i can figure out the rest. Since as you can see from the picture, it contains many objects inside objects and arrays within arrays its very confusing for me to target the specific values i want
I have tried something like this:
$body = $response->getBody();
$data = json_decode($body, true);
$sortedData = $data."hits".hits[0]."_id";
return $sortedData
Also tried without the quotation marks, but i cant really get it to work. Im very new to PHP.

You decoded these objects into associative arrays, so $data['hits']['hits'][0]['_id'] should be the correct way to access that element.
https://www.php.net/manual/en/language.types.array.php explains the basics of how to work with arrays and access elements within them.

Since php 5.5, you can use array_column to get specific column from the array :
$body = $response->getBody();
$data = json_decode($body, true);
$sortedData = array_column($data, '_id');
return $sortedData;
Edit
From what I see on your array sample, you want to do a recursive multidimensional arrays search (not just 2-dimensional).
Assuming you have array like this :
$arr = array(
array(
'x' => '10',
'name' => 'blah',
'other' => array(
'_id' => '26',
'color' => '10x',
)
),
array(
'x' => '7',
'name' => 'blahblah',
'other' => array(
'_id' => '29',
'color' => '7x',
)
),
array(
'x' => '15',
'name' => 'blahblahblah',
'other' => array(
'_id' => '27',
'color' => '15x',
)
),
array(
'x' => '1',
'name' => 'sdf',
'other' => array(
'_id' => '41',
'color' => '1x',
)
),
array(
'x' => '4',
'name' => '3dgdg',
'other' => array(
'_id' => '31',
'color' => '4x',
)
),
array(
'x' => '5',
'name' => 'nmnmnm',
'other' => array(
'_id' => '36',
'color' => '5x',
)
),
array(
'x' => '21',
'name' => 'dhshshhh',
'other' => array(
'_id' => '34',
'color' => '21x',
)
)
);
And you want to get the _id key. In that case you could try this function :
function array_column_recursive(array $haystack, $needle) {
$found = [];
array_walk_recursive($haystack, function($value, $key) use (&$found, $needle) {
if ($key == $needle)
$found[] = $value;
});
return $found;
}
Usage :
$ids = array_column_recursive($arr,'_id');
sort($ids);
print_r($ids);
Reference :
array_column
array_column_recursive

Related

How to extract an array with multiple array keys and values to another array?

Please note that my php version is not 7.
I have an array of arrays like:
array(
'0' => array('id'=>1,'name'=>'abc',"class"=>'xyz'),
'1' => array('id'=>2,'name'=>'abc1',"class"=>'xyz1'),
'2' => array('id'=>3,'name'=>'abc',"class"=>'xyz2'),
);
I want to extract it into two arrays. like
array(
'0' => array('id'=>1,'name'=>'abc'),
'1' => array('id'=>2,'name'=>'abc1'),
'2' => array('id'=>3,'name'=>'abc'),
);
array(
'0' => array('id'=>1,"class"=>'xyz'),
'1' => array('id'=>2,"class"=>'xyz1'),
'2' => array('id'=>3,"class"=>'xyz2'),
);
How can i achieve this, I am in search of some built-in function etc, I studied its supported with array_column but with versions higher than 7.
Edit:
I also tried array_intersect_key and array_slice but its working with single dimensional array.
Then you might want to keep it simple and just use a straight forward foreach loop like this
$old = array(
array('id'=>1,'name'=>'abc',"class"=>'xyz'),
array('id'=>2,'name'=>'abc1',"class"=>'xyz1'),
array('id'=>3,'name'=>'abc',"class"=>'xyz2')
);
foreach ( $old as $temp ) {
$new1 = array('id' => $temp['id'], 'name' => $temp['name']);
$new2 = array('id' => $temp['id'], 'class' => $temp['class']);
}
Use a foreach and add the values to a new array for example:
$idsNames = [];
$idsClasses = [];
$items = [
array('id' => 1, 'name' => 'abc', "class" => 'xyz'),
array('id' => 2, 'name' => 'abc1', "class" => 'xyz1'),
array('id' => 3, 'name' => 'abc', "class" => 'xyz2'),
];
foreach ($items as $item) {
$idsNames[] = ["id" => $item["id"], "name" => $item["name"]];
$idsClasses[] = ["id" => $item["id"], "class" => $item["class"]];
}

php insert key/value into associative array

I'm trying to insert a couple of new Key/Value pairs into an associative array at a specific place. From other reading I've done on SO, I'm pretty sure I have to loop through the array and insert the new values when a condition is set.
Here is the current array
array(
(int) 0 => array(
'Product' => array(
'id' => '59',
'title' => ' Blue Dress',
'Review' => array(
'id' => '7',
'product_id' => '59',
'Review' => array(
(int) 0 => array(
'average' => '3.0000'
)
)
)
)
)
(int) 1 => array(
'Product' => array(
'id' => '60',
'title' => 'Red Dress',
'Review' => array()
)
)
)
The key Review does not always have data, but when it does I want to insert a new key-value similar to the following excerpt
(int) 0 => array(
'Product' => array(
'id' => '59',
'title' => ' Blue Dress',
'Review' => array(
'id' => '7',
'product_id' => '59',
'Review' => array(
(int) 0 => array(
'average' => '3.0000'
'some_value' => '5'
)
)
)
)
)
I've tried a few things without success.
Any help is much appreciated thanks.
You can do something like this:
if(!empty($your_array[index]['Product']['Review'])){
$your_array[index]['Product']['Review']['Review'][index]['some_value'] = 'new_value';
}
In your example it could be:
if(!empty($your_array[0]['Product']['Review'])){
$your_array[0]['Product']['Review']['Review'][0]['some_value'] = 'new_value';
}
Again, you didn't mention your code. So, it's hard to figure out what you want exactly!
You should iterate through Your array and pass current value be reference:
// Notice & sign before variable
foreach ($data as &$product)
{
if ($product['Product']['Review'])
{
// or iterate through Review array
$product['Product']['Review']['Review'][0]['some_value'] = 5;
}
}

CakePHP use Hash to prepare Model array for saving

I'm wondering how one might use CakePHP Hash functions to achieve the following:
This is the array before (Plugin stored in Session):
$Data = array(
'add' => array(
'Certificate' => array(
'name' => '',
'entity_id' => '1',
'state_id' => '18',
'domicile' => '',
'formation_date' => array(
'month' => '',
'day' => '',
'year' => ''
)
)
),
'add2' => array(
'Certificate' => array(
'filing_fees' => '82'
)
)
)
This is the array after. I am reformatting it to call Certificate->save(). I removed the top level and merged the Certificate model.
$Data = array(
'Certificate' => array(
'name' => '',
'entity_id' => '1',
'state_id' => '18',
'domicile' => '',
'formation_date' => array(
'month' => '',
'day' => '',
'year' => ''
),
'filing_fees' => '82'
)
)
This is my current code:
$processed = array();
foreach ($Data as $k => $array1) {
foreach ($array1 as $array1k => $array2) {
if (!isset($processed[$array1k])) {
$processed[$array1k] = array();
}
foreach ($array2 as $a2k => $a2v) {
$processed[$array1k][$a2k] = $a2v;
}
}
}
What I have works, but it's not very "Cake-ish" and will certainly cause problems when I need to prepare data for saving more complex model relationships (e.g. HABTM saveall).
I tried Hash::combine, Hash::merge, array_merge_recursive(), and combinations of these before posting. I understand the PHP logic, but I am lost to find the CakePHP functions with similar logic.
The first step is to merge the Model, then the second step is to remove the key ('add, 'add2'). The closest I got was Hash::combine, but there was no way to reference a $keyPath {s} of the Model, skipping over the first level ('add', 'add2') of the array.
If you could point me in the direction of which Hash or other CakePHP functions are recommended, I'd be happy to take the next step.

Removing selected elements from array of associative arrays

I have the following array of associative arrays.
$result = array(
(int) 0 => array(
'name' => 'Luke',
'id_number' => '1111',
'address' => '1544addr',
'time_here' => '2014-04-12 13:07:08'
),
(int) 1 => array(
'name' => 'Sam',
'id_number' => '2222',
'address' => '1584addr',
'time_here' => '2014-04-12 14:15:26'
I want to remove selected elements from this array such that it will look like this;
array(
(int) 0 => array(
'name' => 'Luke',
'id_number' => '1111'
),
(int) 1 => array(
'name' => 'Sam',
'id_number' => '2222',
This is the code I wrote;
foreach($result as $value)
{
unset($value('address') );
unset($value('time_here') );
}
When I run the code, Apache web server crashed.
Can the smarter members point out what did I do wrong? Thank you very much.
Array notation is wrong, use this;
$finalResult = array();
foreach($result as $value)
{
unset($value['address'] );
unset($value['time_here'] );
$finalResult[] = $value;
}
Here is a working demo: Demo
That is because you are not accessing array correctly. Use square bracket insted of round brackets :
foreach($result as $value)
{
unset($value['address'] );
unset($value['time_here'] );
}

multidimensional array merge operation inside loop

let's say I have two arrays like so:
$array1 = array('A' => array(
'B' => array(
'C' => array(
'D' => array(
'data' => array(
0 => array(
'id' => 1,
'name' => 'name 1'),
1 => array(
'id' => 2,
'name' => 'name 2')))))));
$array2 = array('A' => array(
'B' => array(
'C' => array(
'E' => array(
'data' => array(
0 => array(
'id' => 3,
'name' => 'name 3'),
1 => array(
'id' => 4,
'name' => 'name 4')))))));
As you can see, the two arrays have the same key A, B, and C but the keys are different afterwards. How do I merge these two arrays into something like this:
$final_array = array('A' => array(
'B' => array(
'C' => array(
'D' => array(
'data' => array(
0 => array(
'id' => 1,
'name' => 'name 1'),
1 => array(
'id' => 2,
'name' => 'name 2'))),
'E' => array(
'data' => array(
0 => array(
'id' => 3,
'name' => 'name 3'),
1 => array(
'id' => 4,
'name' => 'name 4')))))));
As you can see, in this case I merge the arrays together into the same array that contains different keys for both. In order words, here I'm putting the array starting from key E from the second array into the array with index C.
Any help will be appreciated, thanks
EDIT: Now, how about if my arrays ($array1, $array2, $array3, $array4, etc...) are generated inside a foreach loop, how do I merge all of those arrays together (Notice that I do not know the number of arrays beforehand)
http://php.net/manual/en/function.array-merge-recursive.php
print_r(array_merge_recursive($array1, $array2));
This should do the trick.
Added:
$collection=array();
foreach() {
$collection[]=$myArray; //here you add your array to collection
}
print_r(call_user_func_array('array_merge_recursive', $collection));
i have not tested this but try this code:
foreach( $array1 as $key => $val )
{
if( !in_array( $key, $array2 ) )
{
$array2[$key] = $val;
}
}
EDIT
use Rok Kralj's answer, using native functions are probably the best way to do this as they are much faster.

Categories