PHP create value variable for json_encode function - php

I'm using a JSON API; I want to create a variable with values and then convert it to a JSON string via json_encode. The (working) JSON string is this:
$data = '
{
"function":"setArticleImages",
"paras":{
"user":"'.$user.'",
"pass":"'.$pass.'",
"product_model":"'.$productsModel.'",
"images":{
"products_id":'.$products_id.',
"image_name":"'.$imageName.'",
"image":"'.$image.'",
"products_images":[{
"products_id":'.$products_id.',
"image_name":"'.$imageName2.'",
"image":"'.$image2.'"
} ]
}
}}
';
I was now trying to write it like this and use json_encode:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
),
)
)
);
$data = json_encode($data);
Unfortunately it does not work. The problems seems to be at '"products_images" => array('. I don't know how to handle the '[' of the '"products_images":[{' part.
Anyone an idea how to write it in the second code snippet?

You just need to add an extra level of array to the products_images element, so that you get a numerically indexed array of associative arrays, giving you the array of objects form you want:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
)
),
)
)
);
Demo on 3v4l.org

The "{ }" in th JSON notation is a PHP array with alphanumerical key.
So :
$array = ["foo" => [1,2,3], "bar" => [4,5,6]
will be converted in a JSON string :
{ foo : [1,2,3], bar: [4,5,6]}
So if you are looking to a JSON that looks like this
[{ foo : [1,2,3], bar: [4,5,6]}]
You will have to do an array with numeric keys that contains your alphanumerical array :
$array = [["foo" => [1,2,3], "bar" => [4,5,6]]];
// same as
$array = [ 0 => ["foo" => [1,2,3], "bar" => [4,5,6]]];

Related

how to display filtered array json by using regular expression in PHP

I have a json array and i want to filter an json object which **state **keys contains this word "ALTS".
<pre>
$arr = array(
array(
"region" => "valore1",
"price" => "valore11",
"state" => "declare par /AMG/OMS/FRA/"
),
array(
"region" => "valore2",
"price" => "valore22",
"state" => "declare par /AMG/OMS/ALTS/"
),
array(
"region" => "valore4",
"price" => "valore44",
"state" => "declare par /AMG/OMS/FRA/"
),
array(
"region" => "valore5",
"price" => "valore55",
"state" => "declare par /AMG/OMS/ALTS/"
),
array(
"region" => "valore3",
"price" => "valore33",
"state" => "declare par /AMG/OMS/ALTS/PT"
)
);
$myJsonArray = json_encode($arr);
echo $myJsonArray;
</pre>
I want to find an example of regular expression which filters this array and only returns an array containing objects with a state containing "/ ALTS".
Any ideas ?
You don't need regex for that. If you find one word you can use strpos function.
$newArr = [];
$findTerm = '/ALTS/';
foreach($arr as $key => $valArr)
{
if(strpos($valArrp['state'], $findTerm) !== false) {
$newArr[] = $valArr;
}
}

Regroup multidimensional array to reverse presentation of many-to-many relationship

I need to perform iterated explosions on values in one column of my two dimensional array, then re-group the data to flip the relational presentation from "tag name -> video id" to "video id -> tag name".
Here is my input array:
$allTags = [
[
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-THREE",
"video" => "64111",
]
];
I want to isolate unique video ids and consolidate all tag names (as comma-separayed values) that relate to each video id.
Expected output:
$allTagsResult = [
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64070",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64076",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64110",
],
[
"name" => "TAG-ONE,TAG-TWO,TAG-THREE",
"video" => "64111",
],
];
Somehow I did it by checking the value using nested loops but I wish to know if you guys can suggest any shortest method to get the expected output.
If you want to completely remove foreach() loops, then using array_map(), array_walk_recursive(), array_fill_keys() etc. can do the job. Although I think that a more straightforward answer using foreach() would probably be faster, but anyway...
$out1 = array_map(function ($data) {
return array_fill_keys(explode(",", $data['video']), $data['name']); },
$allTags);
$out2 = [];
array_walk_recursive( $out1, function ( $data, $key ) use (&$out2) {
if ( isset($out2[$key])) {
$out2[$key]['name'] .= ",".$data;
}
else {
$out2[$key] = [ 'name' => $data, 'video' => $key ];
}
} );
print_r($out2);
will give...
Array
(
[64070] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64070
)
[64076] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64076
)
[64110] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64110
)
[64111] => Array
(
[name] => TAG-ONE,TAG-TWO,TAG-THREE
[video] => 64111
)
)
if you want to remove the keys, then
print_r(array_values($out2));
The code could be compressed by piling all of the code onto single lines, but readability is more useful sometimes.
Another method if you don't like looping:
$video_ids = array_flip(array_unique(explode(",",implode(",",array_column($allTags,'video')))));
$result = array_map(function($id){
return ['name' => '','video' => $id];
},array_flip($video_ids));
array_walk($allTags,function($tag_data) use (&$result,&$video_ids){
$ids = explode(",",$tag_data['video']);
foreach($ids as $id) $result[$video_ids[$id]]['name'] = empty($result[$video_ids[$id]]['name']) ? $tag_data['name'] : $result[$video_ids[$id]]['name'] . "," . $tag_data['name'];
});
Demo: https://3v4l.org/vlIks
Below is one way of doing it.
$allTags = [
'0' => [
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
'1' => [
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
'2' => [
"name" => "TAG-THREE",
"video" => "64111",
]
];
$allTagsResult = array();
$format = array();
foreach( $allTags as $a ) {
$name = $a['name'];
$videos = explode(',', $a['video']);
foreach( $videos as $v ) {
if( !isset( $format[$v]) ) {
$format[$v] = array();
}
$format[$v][] = $name;
}
}
foreach( $format as $video => $names) {
$allTagsResult[] = array('name' => implode(',', $names), 'video' => $video);
}
echo '<pre>';
print_r($allTagsResult);
die;
You can check Demo
I am typically in favor of functional style coding, but for this task I feel it only serves to make the script harder to read and maintain.
Use nested loops and explode the video strings, then group by those video ids and concatenate name strings within each group. When finished iterating, re-index the array.
Code: (Demo)
$result = [];
foreach ($allTags as $tags) {
foreach (explode(',', $tags['video']) as $id) {
if (!isset($result[$id])) {
$result[$id] = ['video' => $id, 'name' => $tags['name']];
} else {
$result[$id]['name'] .= ",{$tags['name']}";
}
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'video' => '64070',
'name' => 'TAG-ONE,TAG-TWO',
),
1 =>
array (
'video' => '64076',
'name' => 'TAG-ONE,TAG-TWO',
),
2 =>
array (
'video' => '64110',
'name' => 'TAG-ONE,TAG-TWO',
),
3 =>
array (
'video' => '64111',
'name' => 'TAG-ONE,TAG-TWO,TAG-THREE',
),
)

Extracting from mulit-array and putting it into my own - php

I'm trying to extract data from a multidimensional array and then putting into one of my own so that I can load it into my database.
Source:
array( "ListOrdersResult" =>
array ( "Orders" =>
array( "Order" =>
array( [0] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
},
[1] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
}
)
)
)
To do this, I'm cycling through it like this - I have no issues with extracting data.
My code:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
$baseArray = $listOrderArray['ListOrdersResult']['Orders']['Order'][$i];
foreach($baseArray as $key => $value) {
if($key == "Title" || $key == "customer_id") {
//ADD TO multidimensional array
}
}
}
How I'm trying to structure it.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
The ultimate goal is to make it easier to load the information into the database by gathering the data by record and then loading it to the database rather than loading by creating an new record and then coming back and modifying that record. To me that seems like it would take more resources and has a higher chance of inconsistent data, but I'm new so I could be wrong.
Any help would be greatly appreciated.
You only have to unset keys you don't want:
$result = array_map(function ($i) {
unset($i['customer_name'], $i['random_info']);
return $i;
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
More about array_map
Or you also can select the keys you want:
$result = array_map(function ($i) {
return ['Title' => $i['Title'], 'customer_id' => $i['customer_id']];
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
About your code and question:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
There's no reason to use a count and a for loop, use foreach.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
doesn't make sense, what are these curly brackets? You should write it like this if you want to be understood:
array(
[0] => array(
"Title" => "fakeTitle0",
"customer_id" => "fakeCustomerId0"
),
[1] => array(
"Title" => "fakeTitle1",
"customer_id" => "fakeCustomerId1"
)
);
You have this initial variable.
$listOrderArray = array(
"ListOrdersResult" => array(
"Orders" => array(
"Order" => array(
0 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
1 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
)
)
)
);
The only thing you should do is to remove the inner array from the three outer arrays.
Here is the solution:
$orders = $listOrderArray['ListOrdersResult']['Orders']['Order'];

PHP Mongodb create Text Index

I am new in MongoDB, and I'm trying to create a text index.
After trying several hours, I have not accomplished anything.
I have an array like this:
//The keys and values are reversed to avoid duplicates in the array keys.
$arr = array(
'Personal' => array(
'PEPE' => "_id",
'd' => array(
"full_name" => "Pedro",
"last_name" => "Picapiedras",
"address"=> "La matanza 123",
"department"=> "Soporte"
), //d end
'PABLO' => "_id",
'd' => array(
"full_name"=> "Pablo",
"last_name"=> "Marmolejo",
"address"=> "Pica 123",
"department"=> "Soporte"
), //d end
)//personal end
);//arr end
I want to create an Index of the _id field so that to edit or view documents, access them through "Pablo" or "Pepe".
Is this possible? Could you give me a hand on how I can do this?
Edit
I have tried with
db.reviews.createIndex( { comments: "text" } )
and
$user = Array(
'_id' => "$id",
'name' => $name,
);
$query = Array( '_id' => "$id" );
$query = Array( '_id' => new MongoId("$id") );
Try this:
$arr = array(
'PEPE' => array(
"_id" => 'PEPE',
'd' => array(
"full_name" => "Pedro",
"last_name" => "Picapiedras",
"address" => "La matanza 123",
"department" => "Soporte"
) //d end
), //PEPE END
'PABLO' => array(
"_id" => 'PABLO',
'd' => array(
"full_name" => "Pablo",
"last_name" => "Marmolejo",
"address" => "Pica 123",
"department" => "Soporte"
), //d end
) // Pablo END
); //$arr end
function insertMongo($array) {
try {
$mongo = new MongoClient();
$db = $mongo -> dbName;
$collection = $db -> collectionName;
$collection -> insert($array);
} catch (MongoCursorException $e) {
die("Query failed ".$e - > getMessage());
}
} //insertMongo
//To execute:
foreach($arr as $a) {
insertMongo($a);
};

Using foreach and nested array to insert rows in MySql with PHP

I've written the follow code to try and insert data into a table on the database. However it's just inserting letters. I'm not sure what I'm doing wrong.
$media_items = array(
array (
"media_name" => "Facebook",
"link_url" => "http://www.facebook.com/insightdezign",
"icon" => "facebook.png",
"size" => "48",
"order" => "0"
),
array (
"media_name" => "Twitter",
"link_url" => "http://www.twitter.com/insightdezign",
"icon" => "twitter.png",
"size" => "48",
"order" => "1"
)
);
foreach ($media_items as $media_item) {
if (is_array($media_item)){
foreach ($media_item as $item) {
$rows_affected = $wpdb->insert( $ffui_items, array( 'media_name' => $item['media_name'], 'link_url' => $item['link_url'], 'icon' => $item['icon'], 'size' => $item['size'], 'order' => $item['order'] ) );
}
}
}
Inside your nested foreach loop, you will be looping over strings, not arrays. As a result of type juggling, the indexes will be evaluated to 0. Since PHP also accepts $foo['bar'] syntax on strings, it will just return the first letter.
You can simply remove the nested foreach loop and do it as follows:
foreach ($media_items as $media_item)
{
if (is_array($media_item))
{
$rows_affected = $wpdb->insert( $ffui_items,
array(
'media_name' => $media_item['media_name'],
'link_url' => $media_item['link_url'],
'icon' => $media_item['icon'],
'size' => $media_item['size'],
'order' => $media_item['order']
) ;
}
}

Categories